Check if string follows order of characters defined by a pattern or not | Set 2 | Python3 program to check if characters of a string follow pattern defined by given pattern . ; Insert all characters of pattern in a hash set , ; Build modified string ( string with characters only from pattern are taken ) ; Remove more than one consecutive occurrences of pattern characters from modified string . ; After above modifications , the length of modified string must be same as pattern length ; And pattern characters must also be same as modified string characters ; Driver Code
def followsPattern ( string , pattern ) : NEW_LINE INDENT patternSet = set ( ) NEW_LINE for i in range ( len ( pattern ) ) : NEW_LINE INDENT patternSet . add ( pattern [ i ] ) NEW_LINE DEDENT modifiedString = string NEW_LINE for i in range ( len ( string ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if not modifiedString [ i ] in patternSet : NEW_LINE INDENT modifiedString = modifiedString [ : i ] + modifiedString [ i + 1 : ] NEW_LINE DEDENT DEDENT for i in range ( len ( modifiedString ) - 1 , 0 , - 1 ) : NEW_LINE INDENT if modifiedString [ i ] == modifiedString [ i - 1 ] : NEW_LINE INDENT modifiedString = modifiedString [ : i ] + modifiedString [ i + 1 : ] NEW_LINE DEDENT DEDENT if len ( pattern ) != len ( modifiedString ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( len ( pattern ) ) : NEW_LINE INDENT if pattern [ i ] != modifiedString [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " engineers ▁ rock " NEW_LINE pattern = " er " NEW_LINE print ( " Expected : ▁ true , ▁ Actual : " , followsPattern ( string , pattern ) ) NEW_LINE string = " engineers ▁ rock " NEW_LINE pattern = " egr " NEW_LINE print ( " Expected : ▁ false , ▁ Actual : " , followsPattern ( string , pattern ) ) NEW_LINE string = " engineers ▁ rock " NEW_LINE pattern = " gsr " NEW_LINE print ( " Expected : ▁ false , ▁ Actual : " , followsPattern ( string , pattern ) ) NEW_LINE string = " engineers ▁ rock " NEW_LINE pattern = " eger " NEW_LINE print ( " Expected : ▁ true , ▁ Actual : " , followsPattern ( string , pattern ) ) NEW_LINE DEDENT