1.题目
给定两个字符串 s 和 t,判断它们是否是同构的。
如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。
所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
示例:
入: s = "egg", t = "add"
输出: true
输入: s = "foo", t = "bar"
输出: false
输入: s = "paper", t = "title"
输出: true
说明:
你可以假设 s 和 t 具有相同的长度。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/isomorphic-strings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
使用Map存储一对一映射。注意两个字符串中的字符都要作为key检查,防止多个字符映射到同一字符。
public class Solution205 {
public boolean isIsomorphic(String s, String t) {
if (s == null && t == null) {
return true;
}
if (s == null || t == null) {
return false;
}
if (s.length() != t.length()) {
return false;
}
return map(s, t) && map(t, s);
}
private boolean map(String s, String t) {
Map<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 {
map.put(s.charAt(i), t.charAt(i));
}
}
return true;
}
}
- 时间复杂度:
- 空间复杂度:,字符为有限多个,一对一映射也是有限的,即常数空间开销。
改进。可将Map改为数组。
public class Solution205 {
public boolean isIsomorphic(String s, String t) {
if (s == null && t == null) {
return true;
}
if (s == null || t == null) {
return false;
}
if (s.length() != t.length()) {
return false;
}
return map(s, t) && map(t, s);
}
private boolean map(String s, String t) {
int[] maps = new int[128];
for (int i = 0; i < s.length(); i++) {
if (maps[s.charAt(i)] == 0) {
maps[s.charAt(i)] = t.charAt(i);
} else {
if (maps[s.charAt(i)] != t.charAt(i)) {
return false;
}
}
}
return true;
}
}