Check if string follows order of characters defined by a pattern or not | Set 3 | Java 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
class GFG { static int CHAR_SIZE = 256 ; static boolean checkPattern ( String str , String pat ) { int [ ] label = new int [ CHAR_SIZE ] ; for ( int i = 0 ; i < CHAR_SIZE ; i ++ ) label [ i ] = - 1 ; int order = 1 ; for ( int i = 0 ; i < pat . length ( ) ; i ++ ) { label [ pat . charAt ( i ) ] = order ; order ++ ; } int last_order = - 1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( label [ str . charAt ( i ) ] != - 1 ) { if ( label [ str . charAt ( i ) ] < last_order ) return false ; last_order = label [ str . charAt ( i ) ] ; } } return true ; } public static void main ( String [ ] args ) { String str = " engineers ▁ rock " ; String pattern = " gsr " ; System . out . println ( checkPattern ( str , pattern ) ) ; } }