Search code examples
javasubsequence

Is String X a sub sequence of String Y Java


Question copied from https://codegolf.stackexchange.com/questions/5529/is-string-x-a-subsequence-of-string-y

T Given strings X and Y, determine whether X is a subsequence of Y. The empty string is regarded as a subsequence of every string. (E.g., '' and 'anna' are subsequences of 'banana'.)

Is their any function already in Java or some common library which does this ?

Input

X, a possibly-empty case-sensitive alphanumeric string Y, a possibly-empty case-sensitive alphanumeric string Output

True or False (or equivalents), correctly indicating whether X is a subsequence of Y. I/O examples

  • '' 'z00' True
  • 'z00' 'z00' True
  • 'z00' '00z0' False
  • 'aa' 'anna' True
  • 'anna' 'banana' True
  • 'Anna' 'banana' False

Solution

  • You could use regexes to check that the sequence is contained in your search string (and using a replace to interleave your search characters with the wildcard .*):

         String x = "anna";
         String y = "banana";
         x = x.replace("", ".*");  //returns .*a.*n.*n.*a.*
    
         System.out.println(y.matches(x));  // returns true