Check if string follows order of characters defined by a pattern or not | Set 3 | C ++ program to find if a string follows order defined by a given pattern . ; Returns true if characters of str follow order defined by a given ptr . ; Initialize all orders as - 1 ; Assign an order to pattern characters according to their appearance in pattern ; give the pattern characters order ; increment the order ; Now one by check if string characters follow above order ; If order of this character is less than order of previous , return false . ; Update last_order for next iteration ; return that str followed pat ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int CHAR_SIZE = 256 ; bool checkPattern ( string str , string pat ) { vector < int > label ( CHAR_SIZE , -1 ) ; int order = 1 ; for ( int i = 0 ; i < pat . length ( ) ; i ++ ) { label [ pat [ i ] ] = order ; order ++ ; } int last_order = -1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( label [ str [ i ] ] != -1 ) { if ( label [ str [ i ] ] < last_order ) return false ; last_order = label [ str [ i ] ] ; } } return true ; } int main ( ) { string str = " engineers ▁ rock " ; string pattern = " gsr " ; cout << boolalpha << checkPattern ( str , pattern ) ; return 0 ; }