Check if string follows order of characters defined by a pattern or not | Set 3 | Python3 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 one 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
CHAR_SIZE = 256 NEW_LINE def checkPattern ( Str , pat ) : NEW_LINE INDENT label = [ - 1 ] * CHAR_SIZE NEW_LINE order = 1 NEW_LINE for i in range ( len ( pat ) ) : NEW_LINE INDENT label [ ord ( pat [ i ] ) ] = order NEW_LINE order += 1 NEW_LINE DEDENT last_order = - 1 NEW_LINE for i in range ( len ( Str ) ) : NEW_LINE INDENT if ( label [ ord ( Str [ i ] ) ] != - 1 ) : NEW_LINE INDENT if ( label [ ord ( Str [ i ] ) ] < last_order ) : NEW_LINE INDENT return False NEW_LINE DEDENT last_order = label [ ord ( Str [ i ] ) ] NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Str = " engineers ▁ rock " NEW_LINE pattern = " gsr " NEW_LINE print ( checkPattern ( Str , pattern ) ) NEW_LINE DEDENT