Check if two given strings are isomorphic to each other | Python program to check if two strings are isomorphic ; This function returns true if str1 and str2 are isomorphic ; Length of both strings must be same for one to one corresponance ; To mark visited characters in str2 ; To store mapping of every character from str1 to that of str2 . Initialize all entries of map as - 1 ; Process all characters one by one ; if current character of str1 is seen first time in it . ; if current character of st2 is already seen , one to one mapping not possible ; Mark current character of str2 as visited ; Store mapping of current characters ; If this is not first appearance of current character in str1 , then check if previous appearance mapped to same character of str2 ; Driver program
MAX_CHARS = 256 NEW_LINE def areIsomorphic ( string1 , string2 ) : NEW_LINE INDENT m = len ( string1 ) NEW_LINE n = len ( string2 ) NEW_LINE if m != n : NEW_LINE INDENT return False NEW_LINE DEDENT marked = [ False ] * MAX_CHARS NEW_LINE map = [ - 1 ] * MAX_CHARS NEW_LINE for i in xrange ( n ) : NEW_LINE INDENT if map [ ord ( string1 [ i ] ) ] == - 1 : NEW_LINE INDENT if marked [ ord ( string2 [ i ] ) ] == True : NEW_LINE INDENT return False NEW_LINE DEDENT marked [ ord ( string2 [ i ] ) ] = True NEW_LINE map [ ord ( string1 [ i ] ) ] = string2 [ i ] NEW_LINE DEDENT elif map [ ord ( string1 [ i ] ) ] != string2 [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT print areIsomorphic ( " aab " , " xxy " ) NEW_LINE print areIsomorphic ( " aab " , " xyz " ) NEW_LINE