Two strings s and t are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
Note, isomorphic mapping is both ways, i.e. in foo and bar; f maps to b but b also maps to f. Lets look at example.
Suppose, we have s as foot and t as baab. If we use 1 map, we have following map
1
2
3
4
5
a --> b
p --> a
p --> a // p already exists in map, map.get(s[i]) == t[i]
l --> b
e --> c
If we just check $s[i]$ matching $t[i]$ (without matching $t[i]$ back to $s[i]$ ) we will see that both strings are isomorphic, but that is incorrect. The reason is both a and l mapped to b.
publicbooleanisIsomorphic(String s, String t) {
if (s ==null&& t ==null)
returntrue;
elseif (s ==null|| t ==null){
returnfalse;
}
if (s.length() != t.length())
returnfalse;
Map<Character, Character> map =new HashMap<> ();
for (int i = 0; i<s.length(); i++) {
char c1 = s.charAt(i);
char c2 = t.charAt(i);
if (map.containsKey(c1)) {
if (map.get(c1) != c2) // if not consistant with previous onesreturnfalse;
} else {
if (map.containsValue(c2)) //if c2 is already being mapped. Time complexity O(n) herereturnfalse;
map.put(c1, c2);
}
}
returntrue;
}
Time complexity:O(n^2) (as containsValue take O(n) and as it is nested under loop, it is O(n^2))