[Oracle] LeetCode 205 Isomorphic Strings
Given two strings s
and t
, determine if they are isomorphic.
Two strings s
and t
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.
Solution
直接用 \(map\) 进行双向的映射即可
点击查看代码
class Solution {
public:
bool isIsomorphic(string s, string t) {
map<char,char> mp1, mp2;
int n1 = s.size(), n2 = t.size();
if(n1!=n2)return false;
else{
for(int i=0;i<n1;i++){
if(mp1.find(s[i])==mp1.end() && mp2.find(t[i])==mp2.end()){
mp1[s[i]]=t[i];
mp2[t[i]]=s[i];
}
else if(mp1.find(s[i])==mp1.end())return false;
else if(mp2.find(t[i])==mp2.end())return false;
else if(mp1.find(s[i])!=mp1.end() && mp2.find(t[i])!=mp2.end()){
//cout<<mp1[s[i]]<<" "<<mp2[t[i]]<<endl;
if(mp1[s[i]]==t[i] && mp2[t[i]]==s[i])continue;
else return false;
}
}
}
return true;
}
};