638. 字符同构
给定两个字符串 s 和 t ,确定它们是否是同构的。
两个字符串是同构的如果 s 中的字符可以被替换得到 t。
所有出现的字符必须用另一个字符代替,同时保留字符串的顺序。 没有两个字符可以映射到同一个字符,但一个字符可以映射到自己。
注意事项
你可以假定两个字符串 s 和 t 是一样长度
的.
样例
给出 s = "egg"
, t= "add"
, 返回 true
。
给出 s = "foo"
, t= "bar"
, 返回 false
。
给出 s = "paper"
, t= "title"
, 返回 true
。
class Solution {
public:
/**
* @param s: a string
* @param t: a string
* @return: true if the characters in s can be replaced to get t or false
*/
bool isIsomorphic(string &s, string &t)
{
//638. 字符同构 write your code here给定两个字符串 s 和 t ,确定它们是否是同构的。
int ns=s.length();
int nt=t.length();
if(ns!=nt) return false;
if(ns==0) return true;
map<char,char> ms,mt;
int i=0;
while(i<ns)
{
if(ms.find(s[i])!=ms.end())
{
if(mt.find(t[i])==mt.end())//!!这种情况不能忘记
{return false;}
else if(ms[s[i]]!=t[i]||mt[t[i]]!=s[i])
return false;
}
else if(mt.find(t[i])!=mt.end())
{
if(ms.find(s[i])==ms.end())
{
return false;
}
else if(ms[s[i]]!=t[i]||mt[t[i]]!=s[i])
return false;
}
else
{
ms[s[i]]=t[i];mt[t[i]]=s[i];
}
i++;
}
return true;
}
};
public:
/**
* @param s: a string
* @param t: a string
* @return: true if the characters in s can be replaced to get t or false
*/
bool isIsomorphic(string &s, string &t)
{
//638. 字符同构 write your code here给定两个字符串 s 和 t ,确定它们是否是同构的。
int ns=s.length();
int nt=t.length();
if(ns!=nt) return false;
if(ns==0) return true;
map<char,char> ms,mt;
int i=0;
while(i<ns)
{
if(ms.find(s[i])!=ms.end())
{
if(mt.find(t[i])==mt.end())//!!这种情况不能忘记
{return false;}
else if(ms[s[i]]!=t[i]||mt[t[i]]!=s[i])
return false;
}
else if(mt.find(t[i])!=mt.end())
{
if(ms.find(s[i])==ms.end())
{
return false;
}
else if(ms[s[i]]!=t[i]||mt[t[i]]!=s[i])
return false;
}
else
{
ms[s[i]]=t[i];mt[t[i]]=s[i];
}
i++;
}
return true;
}
};