[leetcode] Isomorphic Strings

Problem Description:

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.

判断两个字符串是否同构,这里同构定义为存在一个map将字符串S中的所有字符一一映射到字符串T中的所有字符,注意要一一映射。

我的方法是利用额外的空间来记录前面的map,每次遇到一对字符(S和T两个字符串中相同位置的两个字符),检查它们是否在map中出现,以及map信息是否一致。

这里,一定要注意的是只用一个map还不够,比如说S=aa和T=ab,如果只map[T]->S的话,在第一个字符上map[a] = a, 第二个字符上检查map中没有b,所以增加map[b] = a,这样会出现两个字符map到同一个字符,所以不仅要检查map的所有key还要检查value。一个简单的办法是再创建一个map[S]->T。

bool isIsomorphic(string s, string t) {
        if(s.length() != t.length()) return false;
        
        unordered_map<char, char> mapS;
        unordered_map<char, char> mapT;
        for(int i = 0; i < s.length(); ++i)
        {
            if(mapS.find(s[i]) != mapS.end())
            {
                if(mapS[s[i]] != t[i]) return false;
            } else if(mapT.find(t[i]) != mapT.end()){
                if(mapT[t[i]] != s[i]) return false;
            } else {
                mapS[s[i]] = t[i];
                mapT[t[i]] = s[i];
            }
        }
        return true;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值