text: Check if a string can be formed from another string using given constraints | Python3 program to Check if a given string can be formed from another string using given constraints ; Function to check if S2 can be formed of S1 ; length of strings ; hash - table to store count ; store count of each character ; traverse and check for every character ; if the character of s2 is present in s1 ; if the character of s2 is not present in S1 , then check if previous two ASCII characters are present in S1 ; Driver Code ; Calling function to check
code: from collections import defaultdict NEW_LINE def check ( S1 , S2 ) : NEW_LINE INDENT n1 = len ( S1 ) NEW_LINE n2 = len ( S2 ) NEW_LINE mp = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n1 ) : NEW_LINE INDENT mp [ S1 [ i ] ] += 1 NEW_LINE DEDENT for i in range ( 0 , n2 ) : NEW_LINE INDENT if mp [ S2 [ i ] ] : NEW_LINE INDENT mp [ S2 [ i ] ] -= 1 NEW_LINE DEDENT elif ( mp [ chr ( ord ( S2 [ i ] ) - 1 ) ] and mp [ chr ( ord ( S2 [ i ] ) - 2 ) ] ) : NEW_LINE INDENT mp [ chr ( ord ( S2 [ i ] ) - 1 ) ] -= 1 NEW_LINE mp [ chr ( ord ( S2 [ i ] ) - 2 ) ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S1 = " abbat " NEW_LINE S2 = " cat " NEW_LINE if check ( S1 , S2 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT