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.
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 中的字符。不能一对多,也不能多对一。
利用两个map实现。
代码如下:
class Solution {
public:
bool isIsomorphic(string s, string t) {
map<char, char> mapA;
map<char, char> mapB;
int n = s.length();
for(int i = ; i < n; i++)
{
char ss = s[i];
char tt = t[i];
map<char, char>::iterator it = mapA.find(ss);
if(it != mapA.end())
{
if(mapA[ss] != tt)
{
return false;
}
}
else
{
map<char, char>::iterator ii = mapB.find(tt);
if(ii != mapB.end() && mapB[tt] != ss)
{
return false;
}
else
{
mapA[ss] = tt;
mapB[tt] = ss;
}
}
}
return true;
}
};