LeetCode 205. Isomorphic Strings

来源:互联网 发布:网络摄像机组装配件 编辑:程序博客网 时间:2024/06/09 13:13

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.


分析:

定义两个键值对m1,m2。m1表示s到t的映射,m2表示t到s的映射,如果当前字符已经被映射,并且值不等于

class Solution {public:    bool isIsomorphic(string s, string t) {        int n=s.length();        map<char,char> m1;        map<char,char> m2;        cout<<n<<endl;        for(int i=0;i<n;i++){            if((m1.count(s[i])>0&& m1[s[i]] != t[i] )||( m2.count(t[i])>0&& m2[t[i]] != s[i]))                return false;            m1[s[i]]=t[i];            m2[t[i]]=s[i];        }        return true;    }};