其实就是一一映射问题
哈希表映
初始代码:
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char, char> m;
unordered_set<char> set;
for(int i = 0; i < s.size(); ++i){
if(m.count(s[i]) && m[s[i]] != t[i]) return false;
else if(m[s[i]] != t[i] && set.count(t[i])) return false;//已经有字符映射到t[i]了
else{
m[s[i]] = t[i];
set.insert(t[i]);//表示有字符映射到t[i]了
}
}
return true;
}
};
下面进行优化,set可以先去掉:
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char, char> m;
for(int i = 0; i < s.size(); ++i){
if(m.count(s[i])){
if(m[s[i]] != t[i]) return false;
}
else{//s[i]不再map中
for(auto v : m){
if(v.second == t[i]) return false;//已经有元素指向t[i]
}
m[s[i]] = t[i]; //s[i]不在map中,也没有元素指向t[i]
}
}
return true;
}
};
可以使用数组代替哈希表:
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector<int> m(128, -1);
for(int i = 0; i < s.size(); ++i){
if(m[s[i]] != -1){
if(m[s[i]] != t[i]) return false;
}
else{//s[i]不再map中
for(auto v : m){
if(v == t[i]) return false;//已经有元素指向t[i]
}
m[s[i]] = t[i]; //s[i]不在map中,也没有元素指向t[i]
}
}
return true;
}
};
上面的循环检测有没有元素指向t[i]可以再使用一个数组完成O(1)的查询:
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector<int> m(128, -1);//用于建立映射
vector<int> n(128, 0);//用于记录哪些元素已经有元素指向了
for(int i = 0; i < s.size(); ++i){
if(m[s[i]] != -1){
if(m[s[i]] != t[i]) return false;
}
else{//s[i]不再map中
if(n[t[i]]) return false;//已经有元素指向t[i]
m[s[i]] = t[i]; //s[i]不在map中,也没有元素指向t[i]
n[t[i]] = 1;//置位,表示已有元素指向t[i]
}
}
return true;
}
};
使用查找
很短也很快还很小
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.size() == 0) return true;
for (int i = 0; i < s.size(); i++){
if (s.find(s[i]) != t.find(t[i])) return false;//第一次出现的位置
}
return true;
}
};
字符串的find函数并不是O(1)的,可以修改如下:
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector<int> m(128, -1);
vector<int> n(128, -1);
for (int i = 0; i < s.size(); i++){
if(m[s[i]] == -1) m[s[i]] = i;//记录第一次出现的位置
if(n[t[i]] == -1) n[t[i]] = i;
if(m[s[i]] != n[t[i]]) return false;
}
return true;
}
};