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是否是同构的。
如果s中的某一个字符对应着t里的某一个字符并且t里面的某一个字符也只对应着s里的某一个字符,那么s和t是同构的。
比如add和egg,a对应e,d对应g,两个字符串同构。
再比如ad和aa,如果只从s的角度看,a对应着一个字符a,d对应着一个字符a,可以。但从t的角度看,第一个字符a对应a,第二个字符a对应d,两个字符对应到了相同的字符,不是同构的。所以我们可以用两个map结构,一个存储s2t的对应关系,一个存储t2s的对应关系。
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.size() != t.size()) return false;
unordered_map<char, char> s2t;
unordered_map<char, char> t2s;
for(int i = 0; i < s.size(); i ++){
if(s2t.find(s[i]) == s2t.end()){//c1不在
s2t.insert({s[i], t[i]});
}
else{//s[i]已在map中,判断其对应的value是否等于t[i]
if(s2t[s[i]] != t[i])
return false;
}
if(t2s.find(t[i]) == t2s.end()){
t2s.insert({t[i], s[i]});
}
else{
if(t2s[t[i]] != s[i])
return false;
}
}
return true;
}
};