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.


 They key point to store the index of each character. If next round doesn't match, it is false.

    bool isIsomorphic(string s, string t) {
        if(s.size() != t.size()) return false;
        vector<int> sMap(256, 0);
        vector<int> tMap(256, 0);
        for(int i = 0; i < s.size(); ++i) {
            int s_t = (int)s[i];
            int t_t = (int)t[i];
            if(sMap[s_t] != tMap[t_t]) return false;
            if((sMap[s_t] == 0) && (tMap[t_t] == 0)) {
                sMap[s_t] = i + 1;
                tMap[t_t] = i + 1;   // here, it is important here to start from non-zero.
            }
        }
        return true;
    }


你可能感兴趣的:(LeetCode 205. Isomorphic Strings)