Leetcode 205. Isomorphic Strings

来源:互联网 发布:网络捕鱼推广技巧 编辑:程序博客网 时间:2024/06/06 09:51

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;    }};
0 0
原创粉丝点击