Two strings are said to be isomorphic if it is possible to map every character of the first string to every character of the second string. Basically, in isomorphic strings, there is a one-to-one mapping between every character of the first string to every character of the second string.
str1 = 'ABCA' str2 = 'XYZX' 'A' maps to 'X' 'B' maps to 'Y' 'C' maps to 'Z'
Here, mapping is possible between every character of the first string to every character of the second string. So str1 and str2 are isomorphic.
str1 = 'ABCA' str2 = 'WXYZ' 'A' maps to 'W' 'B' maps to 'X' 'C' maps to 'Y' 'A' again maps to 'Z'
These two strings are not isomorphic because character ‘A’ from the first string is mapping with two characters from the second string.
One possible way to check isomorphic strings is if we can replace each character of the first string with a character to get the second string and vice versa.
Approach: To check if strings are isomorphic or not, we have to take care of the following conditions:
- The length of both strings should be equal
- The current character of both strings shouldn’t be mapped with other characters already.
We will use a hashmap to store the mapping between characters from str1 to those of str2. We will also use a Set to store the already mapped characters of str2.
Below is the implementation of the above approach.