If every character in one string can be mapped to every character in another string, then the two strings are isomorphic. To put it simply, in isomorphic strings, each character in the first string corresponds exactly to each character in the second string.
To determine whether or not strings are isomorphic, we need to make sure that the following conditions are met:
- The length of both strings must be equal.
- The character currently being used in both strings shouldn’t be mapped with any other characters.
Example 1 – isomorphic strings:
str1 = ‘ABCA’
str2 = ‘XYZX’
‘A’ maps to ‘X’
‘B’ maps to ‘Y’
‘C’ maps to ‘Z’
When this occurs, every character in the first string can be mapped to every character in the second string. Therefore, str1 and str2 are isomorphic.
Example 2 – non-isomorphic strings:
str1 = ‘ABCA’
str2 = ‘WXYZ’
‘A’ maps to ‘W’
‘B’ maps to ‘X’
‘C’ maps to ‘Y’
‘A’ again maps to ‘Z’
Since character ‘A’ from the first string is mapping with two characters from the second string, these two strings do not possess an isomorphic relationship with one another.
A common method for determining whether or not two strings are isomorphic is to see if they can be constructed by exchanging each character in one string with a character in the other. If so, then the strings are isomorphic.
You can also utilize a hashmap to hold the mapping between str1 and str2 characters. Another way to map the strings is to employ a set to store the str2 characters that have previously been mapped.
Final word on checking to see if strings are isomorphic