Two Strings are called isomorphic if the letters in one String can be remapped to get the second String. Remapping a letter means replacing all occurrences of it with another letter. The ordering of the letters remains unchanged. The mapping is two way and no two letters may map to the same letter, but a letter may map to itself. Determine if two given String are isomorphic.
Assumptions:
- The two given Strings are not null.
Examples:
"abca" and "xyzx" are isomorphic since the mapping is 'a' <-> 'x', 'b' <-> 'y', 'c' <-> 'z'.
"abba" and "cccc" are not isomorphic.
Solution: 注意字母之间要一一对应,所以要s和t各扫一次
public boolean isomorphic(String s, String t) {
if (s.length() != t.length()) {
return false;
}
return helper(s, t) && helper(t, s);
}
private boolean helper(String s, String t) {
Map<Character, Character> hashmap = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c1 = s.charAt(i), c2 = t.charAt(i);
if (!hashmap.containsKey(c1)) {
hashmap.put(c1, c2);
} else if (hashmap.get(c1) != c2) {
return false;
}
}
return true;
}