205. Isomorphic Strings
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
Example 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both s and t have the same length.
方法1: two hash
思路:
见了两个hash map, 因为必须保证双向一一对应。
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char, char> hash;
unordered_map<char, char> hash_r;
for (int i = 0; i < s.size(); i++){
if (hash.find(s[i]) == hash.end()){
hash[s[i]] = t[i];
}
if (hash_r.find(t[i]) == hash_r.end()){
hash_r[t[i]] = s[i];
}
if (hash[s[i]] != t[i] || hash_r[t[i]] != s[i]){
return false;
}
}
return true;
}
};
class Solution{
public:
bool isIsomorphic(string s, string t) {
if (s.size() != t.size()) return false;
vector<int> hash1(256, -1);
vector<int> hash2(256, -1);
for (int i = 0; i < s.size(); i++) {
if (hash1[(int)s[i]] == -1 && hash2[(int)t[i]] == -1) {
hash1[(int)s[i]] = t[i];
hash2[(int)t[i]] = s[i];
continue;
}
if (hash1[(int)s[i]] != t[i] || hash2[(int)t[i]] != s[i]) return false;
}
return true;
}
};
方法2:
夏洛的网:https://blog.youkuaiyun.com/liuxiao214/article/details/77587070
思路:
这个方法很巧妙,用两个vector来记录每个字母出现的index。当一对映射出现时,将他们的值都改成两者的坐标。因为初始化都是-1,所以第一次字符对出现都会成功建立坐标。当第二次这对映射再出现(不用管来自哪个字符串),只要他们的坐标相等,表示他们之前也被映射在一起,此时将这对的坐标再次更新。但是当两者不等,如果都不是-1,说明他们上一次并不在同一个映射中出现,如果其中一个不是-1,说明有个字符没出现,另一个已经被映射到了别人。都要返回false。
class Solution104_2 {
public:
bool isIsomorphic(string s, string t) {
vector<int>v1(256, -1);
vector<int>v2(256, -1);
for (int i = 0; i < s.length();i++)
{
if (v1[s[i]] != v2[t[i]])
return false;
v1[s[i]] = i;
v2[t[i]] = i;
}
return true;
}
};