leetcode_Isomorphic Strings _easy

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.



方法:使用2个map就可以。


class Solution {
public:
    bool isIsomorphic(string s, string t) {
        map<char,char> ccmap,ccmap2;
        int i=s.length(),j=t.length();
        if(i==j)
        {
            for(int m=0; m<i; m++)
            {
                map<char,char>::iterator iter=ccmap.find(s[m]);
                if(iter!=ccmap.end())//找到。此字符之前已经作为原始字符在替换中用过
                {
                    if((*iter).second!=t[m])
                        return false;
                }
                else
                    ccmap[s[m]]=t[m];
            }
            //通过map推断是否存在那种aa, ba这种情况导致的多个字符映射到同一个字符的错误。假设存在,那么返回false
            int len=ccmap.size(),len2;
            //将ccmap中的key和value进行调换位置赋值给ccmap2,ccma自己不变
            for(map<char,char>::iterator iter=ccmap.begin(); iter!=ccmap.end(); iter++)
                ccmap2[(*iter).second]=(*iter).first;
            len2=ccmap2.size();
            if(len!=len2)//长度不等。那么说明ccmap中存在value相等的元素(如aa,ba: a-->b, a-->a,false)
                return false;//
            return true;
        }
        return false;
    }
};



转载于:https://www.cnblogs.com/mfmdaoyou/p/6897479.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值