Leetcode 205. Isomorphic Strings

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思路:
1. isomorphic表示同质,对string来说,就是结构相同,里面的字母是谁不重要,比如:abb和cdd就是isomorphic,因为形式上是一样的。如何判断呢?
2. 略微思考,有点没有眉目,开始有点细微的紧张。不过还好,做得多了,有底气了,和这些情绪都相处得很好。回到正题,两个string同时遍历,例如:”paper”, “title”,把p映射成t,a映射成i,第二次遇到p时,就查询之前p映射的是多少,和现在打算映射的值是否一致。如果能通过所有一致性检查,说明就是isomorphic的;中间任何地方不一致,就不是!
3. 代码第一次写的时候,默认只用一个unordered_map来存s[i]->t[i]的映射,但是对”agg”和”ggg”则不正确了,还需要存t[i]->s[i]的映射,因为只有这个映射,a和g映射成g都是合法的,但题目要求,不允许两个字母映射成一个字母。因此需要两个map来保存相互的映射关系最保险!

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        //
        unordered_map<char,char> mm1,mm2;
        int i=s.size();
        for(int i=0;i<s.size();i++){
            if(mm1.count(s[i])){
                if(mm1[s[i]]!=t[i]) return false;
            }else if(mm2.count(t[i])){
                if(mm2[t[i]]!=s[i]) return false;
            }
            else{
                mm1[s[i]]=t[i];
                mm2[t[i]]=s[i];
            }

        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值