Check if string follows order of characters defined by a pattern or not | Set 1 | C ++ 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
#include <iostream> NEW_LINE using namespace std ; bool 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 [ i ] ; char y = pattern [ i + 1 ] ; size_t last = str . find_last_of ( x ) ; size_t first = str . find_first_of ( y ) ; if ( last == string :: npos first == string :: npos last > first ) return false ; } return true ; } int main ( ) { string str = " engineers ▁ rock " ; string pattern = " gsr " ; cout << boolalpha << checkPattern ( str , pattern ) ; return 0 ; }