Friday, May 1, 2015

205. Isomorphic Strings -E

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.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both and have the same length.
A:
就是两个一一映射的关系。
用2个mapping就行了

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        return helper(s,t) && helper(t,s);
    }
private:
    bool helper(string s, string t)
    {
        map<char, char> mymap;
        for(int i =0;i<s.length();++i)
        {
            char ch1 = s[i];
            char ch2 = t[i];
            if(mymap.find(ch1)==mymap.end()) // first time find
            {
                mymap.insert({ch1,ch2});
            }else{
                if(mymap.find(ch1)->second != ch2)
                {
                    return false;
                }
            }
        }
        return true;
    }
};


通常的做法就是用2个map,这样就不用call 2 遍。

还有就是不用map, 直接用array, 用char 的值做index.


No comments:

Post a Comment