Check if a string can be made equal to another string by swapping or replacement of characters | Function to find if given strings are same or not ; Base Condition ; Stores frequency of characters of the str1 and str2 ; Traverse strings str1 & str2 and store frequencies in a [ ] and b [ ] ; Check if both strings have same characters or not ; If a character is present in one and is not in another string , return false ; Sort the array a [ ] and b [ ] ; Check arrays a and b contain the same frequency or not ; If the frequencies are not the same after sorting ; At this point , str1 can be converted to str2 ; Driver Code
def sameStrings ( str1 , str2 ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE M = len ( str2 ) NEW_LINE if ( N != M ) : NEW_LINE INDENT return False NEW_LINE DEDENT a , b = [ 0 ] * 256 , [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT a [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE b [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT i = 0 NEW_LINE while ( i < 256 ) : NEW_LINE INDENT if ( ( a [ i ] == 0 and b [ i ] == 0 ) or ( a [ i ] != 0 and b [ i ] != 0 ) ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT a = sorted ( a ) NEW_LINE b = sorted ( b ) NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT if ( a [ i ] != b [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S1 , S2 = " cabbba " , " abbccc " NEW_LINE if ( sameStrings ( S1 , S2 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT