直接做,过了
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<int, vector<int>> vs;
unordered_map<int, vector<int>> vt;
int m = s.size(), n = t.size();
if(m != n)
return false;
for(int i = 0; i < m; i++){
vs[s[i]].emplace_back(i);
vt[t[i]].emplace_back(i);
}
for(int i = 0; i < m; i++){
if(vs[s[i]] != vt[t[i]])
return false;
}
return true;
}
};
其实只要比较每一个字符前一次出现的位置是否对应就行。如果两个字符都是第一次出现,前一个位置都是0,就通过。所以位置从1开始记,避开0。
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector<int> spre(256,0);
vector<int> tpre(256,0);
for(int i = 0; i < s.length(); i++){
if(spre[s[i]] != tpre[t[i]])
return false;
spre[s[i]] = tpre[t[i]]= i + 1;
}
return true;
}
};