Check if a given string can be converted to another by given possible swaps | Python3 program to implement the above approach ; Stores length of str1 ; Stores length of str2 ; Stores distinct characters of str1 ; Stores distinct characters of str2 ; Stores frequency of each character of str1 ; Traverse the string str1 ; Update frequency of str1 [ i ] ; Traverse the string str1 ; Insert str1 [ i ] into st1 ; Traverse the string str2 ; Insert str1 [ i ] into st1 ; If distinct characters in str1 and str2 are not same ; Stores frequency of each character of str2 ; Traverse the string str2 ; Update frequency of str2 [ i ] ; Sort hash1 [ ] array ; Sort hash2 [ ] array ; Traverse hash1 [ ] and hash2 [ ] ; If hash1 [ i ] not equal to hash2 [ i ] ; Driver Code
def checkStr1CanConStr2 ( str1 , str2 ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE M = len ( str2 ) NEW_LINE st1 = set ( [ ] ) NEW_LINE st2 = set ( [ ] ) NEW_LINE hash1 = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT hash1 [ ord ( str1 [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT st1 . add ( str1 [ i ] ) NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT st2 . add ( str2 [ i ] ) NEW_LINE DEDENT if ( st1 != st2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT hash2 = [ 0 ] * 256 NEW_LINE for i in range ( M ) : NEW_LINE INDENT hash2 [ ord ( str2 [ i ] ) ] += 1 NEW_LINE DEDENT hash1 . sort ( ) NEW_LINE hash2 . sort ( ) NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT if ( hash1 [ i ] != hash2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " xyyzzlll " NEW_LINE str2 = " yllzzxxx " NEW_LINE if ( checkStr1CanConStr2 ( str1 , str2 ) ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT DEDENT