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.
Example 1:
Input: s = “egg”, t = “add”
Output: true
Example 2:
Input: s = “foo”, t = “bar”
Output: false
给出两个字符串s和t,判断是否同构,即s中的字母能被t中对应的字母替换而不改变结构
思路:
可以用HashMap保存s和t对应位置字符(s[i], t[i])
当s[i]存在于map的key中,而value != t[i],则返回false
否则在map中加入(s[i], t[i])
注意下面的例子:
s = ab
t = aa
s[1] = b 不存在于map,但是注意到t[i]是已经存在于value里的,而t[1]=a应该对应a,此时却对应的是b,返回false
因此不仅要check key,当key不存在时还要check value
public boolean isIsomorphic(String s, String t) {
if(s == null || t == null || s.length() != t.length()) {
return false;
}
HashMap<Character, Character> map = new HashMap<>();
for(int i = 0; i < s.length(); i++) {
if(map.containsKey(s.charAt(i))) {
if(map.get(s.charAt(i)) != t.charAt(i)) {
return false;
}
} else if(map.containsValue(t.charAt(i))) {
return false;
} else {
map.put(s.charAt(i), t.charAt(i));
}
}
return true;
}
如果追求更少的time complexity,因为字符只有26个,可以用数组保存每个字符对应的index,当对应的index不一致时返回false