Given two strings s and t, determine if they are isomorphic.
Two strings 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.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
思路:分别存储s到t和t到s的字符映射,然后分别用映射生成对应的映射字符串,最后比较两个映射字符串是否与t和s相同。
public boolean isIsomorphic(String s, String t) {
if (s == null || t == null || s.length() != t.length()) {
return false;
}
//use map to store the relation
Map<Character, Character> smap = new HashMap<>();
Map<Character, Character> tmap = new HashMap<>();
//iterate s to gen a new string according to the map
StringBuilder ms = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char sc = s.charAt(i);
if (smap.containsKey(sc)) {
ms.append(smap.get(sc));
} else {
char tc = t.charAt(i);
smap.put(sc, tc);
tmap.put(tc, sc);
ms.append(tc);
}
}
StringBuilder mt = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
mt.append(tmap.get(t.charAt(i)));
}
return ms.toString().equals(t) && mt.toString().equals(s);
}
网友评论