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.
分析:
定义两个键值对m1,m2。m1表示s到t的映射,m2表示t到s的映射,如果当前字符已经被映射,并且值不等于
class Solution {
public:
bool isIsomorphic(string s, string t) {
int n=s.length();
map<char,char> m1;
map<char,char> m2;
cout<<n<<endl;
for(int i=0;i<n;i++){
if((m1.count(s[i])>0&& m1[s[i]] != t[i] )||( m2.count(t[i])>0&& m2[t[i]] != s[i]))
return false;
m1[s[i]]=t[i];
m2[t[i]]=s[i];
}
return true;
}
};
本文介绍了一种算法,用于判断两个给定的字符串是否为同构字符串。通过使用两个映射表来跟踪不同字符串间的字符对应关系,确保了所有出现的相同字符都被一致地替换。
1413

被折叠的 条评论
为什么被折叠?



