638. 字符同构

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;
}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值