2015年6月7日星期日

LeetCode: Isomorphic Strings

This problem is solve with key-value structure.
The smap stored key from char in s.
The tmap stroed key from char in t. The effect of tmap is just to make sure that values in tmap are not repeated. So I used a set replace the tmap. ( annotations are how to use tmap)
If changing map and set to unordered, speed will be better.

From the leetcode performance, there should be quicker way...

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    bool isIsomorphic(string s, string t) {
        map<char, char> smap;
        //map<char, char> tmap;
        set<char> sset;
        for(int i=0;i<s.size();i++){
            if(!smap.count(s[i])) {
                //if( tmap.count(t[i])) return false;
                if( sset.count(t[i])) return false;
                smap[s[i]]=t[i];
                //tmap[t[i]]=s[i];
                sset.insert(t[i]);
            }
            else if(smap.find(s[i])->second!=t[i]) return false;
        }
        return true;
    }
};
Reference:
http://www.bkjia.com/cjjc/994501.html

没有评论:

发表评论