題目來源
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.
For example,
Given "egg"
, "add"
, return true.
Given "foo"
, "bar"
, return false.
Given "paper"
, "title"
, return true.
Note:
You may assume both s and t have the same length.
然后我想了一個非常弱的解決方案…遍歷,兩個哈希表來記錄s到t,t到s的映射關系,假如關系不對,就返回false。雖然A了,但是還是有點亂…再想想。
class Solution {
public:
bool isIsomorphic(string s, string t) {
int n = s.size();
unordered_map<char, char> map1;
unordered_map<char, char> map2;
for (int i=0; i<n; i++) {
if (!map1[s[i]] && !map2[t[i]]) {
map1[s[i]] = t[i];
map2[t[i]] = s[i];
}
else {
if (map1[s[i]] != t[i] && map2[t[i]] != s[i])
return false;
}
}
return true;
}
};
然后實際上只需要記錄當前字母前一次出現的位置就可以了,代碼如下:
class Solution {
public:
bool isIsomorphic(string s, string t) {
int n = s.size();
vector<int> m1(256, 0);
vector<int> m2(256, 0);
for (int i=0; i<n; i++) {
if (m1[s[i]] != m2[t[i]])
return false;
m1[s[i]] = i + 1;
m2[t[i]] = i + 1;
}
return true;
}
};