Check if string follows order of characters defined by a pattern or not | Set 1 | Java program check if characters in the input string follows the same order as determined by characters present in the given pattern ; Function to check if characters in the input string follows the same order as determined by characters present in the given pattern ; len stores length of the given pattern ; if length of pattern is more than length of input string , return false ; ; x , y are two adjacent characters in pattern ; find index of last occurrence of character x in the input string ; find index of first occurrence of character y in the input string ; return false if x or y are not present in the input string OR last occurrence of x is after the first occurrence of y in the input string ; return true if string matches the pattern ; Driver code
class GFG { static boolean checkPattern ( String str , String pattern ) { int len = pattern . length ( ) ; if ( str . length ( ) < len ) { return false ; } for ( int i = 0 ; i < len - 1 ; i ++ ) { char x = pattern . charAt ( i ) ; char y = pattern . charAt ( i + 1 ) ; int last = str . lastIndexOf ( x ) ; int first = str . indexOf ( y ) ; if ( last == - 1 first == - 1 last > first ) { return false ; } } return true ; } public static void main ( String [ ] args ) { String str = " engineers ▁ rock " ; String pattern = " gsr " ; System . out . println ( checkPattern ( str , pattern ) ) ; } }