Skip to content

Instantly share code, notes, and snippets.

@liweiwei1419
Created May 21, 2018 06:53
Show Gist options
  • Save liweiwei1419/83bdc86fbc76f77c8db32b05711e57a8 to your computer and use it in GitHub Desktop.
Save liweiwei1419/83bdc86fbc76f77c8db32b05711e57a8 to your computer and use it in GitHub Desktop.
LeetCode 第 205 题题解。
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
// https://leetcode-cn.com/problems/isomorphic-strings/description/
public class Solution {
// 两个字符不能映射到同一个字符上,但字符可以映射自己本身
// 正例:ab cd
// 反例:ab cc
public boolean isIsomorphic(String s, String t) {
int len = s.length();
if (len != t.length()) {
return false;
}
Set<Character> set = new HashSet<>();
Map<Character, Character> map = new HashMap<>();
for (int i = 0; i < len; i++) {
Character curS = s.charAt(i);
Character curT = t.charAt(i);
if (!map.containsKey(curS)) {
map.put(curS, curT);
if (!set.contains(curT)) {
set.add(curT);
} else {
return false;
}
} else {// 如果当前遍历的字符以前出现过,检查取出的 value 是否匹配
if (map.get(curS) != curT) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
Solution solution = new Solution();
String s = "ab";
String t = "cc";
boolean isomorphic = solution.isIsomorphic(s, t);
System.out.println(isomorphic);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment