[LinkedIn]Isomorphic Strings
From Here
Given two (dictionary) words as Strings, determine if they are isomorphic.
Two words are called isomorphic if the letters in one word can be remapped to get the second word. Remapping a letter means replacing all occurrences of it with another letter while the ordering of the letters remains unchanged. No two letters may map to the same letter, but a letter may map to itself.
Wrong Solution:
map char to char, then check in the hashmap. However, this will not work!
since no two letters may map to the same letter. This will damage the rule
Best solution:
HashMap (char, firstSeenIndice) for each string. The encoding of firstSeenIndices should match.
E.g. Foo and app both encode to 011
Abcd and hole both encode to 0123
public boolean isomorphic(String s, String t) {
if (s.length() != t.length()) {
return false;
}
return (sequence(s).equals(sequence(t)));
}
private String sequence(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
sb.append(map.get(s.charAt(i)));
} else {
map.put(s.charAt(i), i);
}
}
return sb.toString();
}