Title:Isomorphic Strings 205
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/isomorphic-strings/
1. Map + Set
时间复杂度:O(n),一层for循环,最长遍历为字符串的长度。
空间复杂度:O(n),申请Map和Set。
/**
* Map<s[i],t[i]>维护映射关系,Set维护map中value是否出现过(如果出现过就是多对一的映射关系,返回false)
* @param s
* @param t
* @return
*/
public static boolean isIsomorphic(String s, String t) {
if (s == null && t == null) {
return true;
}
else if (s == null || t == null) {
return false;
}
else if (s.length() == 0 && t.length() == 0) {
return true;
}
else if (s.length() != t.length()) {
return false;
}
Map<Character, Character> map = new HashMap<>();
Set<Character> set = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
char sc = s.charAt(i);
char tc = t.charAt(i);
if (!map.containsKey(sc)) {
if (set.contains(tc)) {
return false;
}
else {
map.put(sc, tc);
set.add(tc);
}
}
else {
if (map.get(sc) != tc) {
return false;
}
}
}
return true;
}