LeetCode 205. Isomorphic Strings(C++版)

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是否是同构的。

如果s中的某一个字符对应着t里的某一个字符并且t里面的某一个字符也只对应着s里的某一个字符,那么s和t是同构的。

比如add和egg,a对应e,d对应g,两个字符串同构。

再比如ad和aa,如果只从s的角度看,a对应着一个字符a,d对应着一个字符a,可以。但从t的角度看,第一个字符a对应a,第二个字符a对应d,两个字符对应到了相同的字符,不是同构的。所以我们可以用两个map结构,一个存储s2t的对应关系,一个存储t2s的对应关系。

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if(s.size() != t.size()) return false;
        
        unordered_map<char, char> s2t;
        unordered_map<char, char> t2s;
        
        for(int i = 0; i < s.size(); i ++){
            if(s2t.find(s[i]) == s2t.end()){//c1不在
                s2t.insert({s[i], t[i]});
            }
            else{//s[i]已在map中,判断其对应的value是否等于t[i]
                if(s2t[s[i]] != t[i])
                    return false;
            }
            
            if(t2s.find(t[i]) == t2s.end()){
                t2s.insert({t[i], s[i]});
            }
            else{
                if(t2s[t[i]] != s[i])
                    return false;
            }
                
        }
        return true;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值