205. Isomorphic Strings
2018-02-28 本文已影响7人
衣介书生
题目分析
原题链接,登录 LeetCode 后可用
这道题目让我们判断两个字符串是否是同构字符串。示例如下:
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
解题思路是用两个 Map 记录两个字符串中的字符的映射关系。
代码
class Solution {
public boolean isIsomorphic(String s, String t) {
Map<Character, Character> hm1 = new HashMap<Character, Character>();
Map<Character, Character> hm2 = new HashMap<Character, Character>();
for(int i = 0; i < s.length(); i++) {
char c1 = s.charAt(i);
char c2 = t.charAt(i);
if(hm1.containsKey(c1)) {
if(hm1.get(c1) != c2) {
return false;
}
}
if(hm2.containsKey(c2)) {
if(hm2.get(c2) != c1) {
return false;
}
}
hm1.put(c1, c2);
hm2.put(c2, c1);
}
return true;
}
}