方法一:判断每个字符首次出现的位置 复杂度(O(n^2))
class Solution {
public:
bool isIsomorphic(string s, string t) {
for (int i = 0; i < s.length(); i++){
if (s.find(s[i]) != t.find(t[i])) return false;
}
return true;
}
};
方法二:双hash 时间复杂度O(n)
具体思路: 依次遍历形成s[i]->t[i]的hash和t[i]->s[i]的双hash,遍历到新的一对时,如果s[i]->…或者t[i]->…已经出现过则返回false
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char, char> ump1, ump2;
int n = s.size();
for (int i = 0; i < n; ++i) {
if (ump1.count(s[i]) && ump1[s[i]] != t[i]) return false;
if (ump2.count(t[i]) && ump2[t[i]] != s[i]) return false;
ump1[s[i]] = t[i];
ump2[t[i]] = s[i];
}
return true;
}
};