Easy solution with one hash table using C++


  • 0
    W
    bool isIsomorphic(string s, string t) {
            if (s.size() != t.size()) return false;
            unordered_map<string, string> hashtbl;
            string tmp1 = "s";
            string tmp2 = "t";
            for (int i=0; i<s.size(); i++) {
                tmp1.push_back(s[i]);
                tmp2.push_back(t[i]);
                if (hashtbl.find(tmp1) != hashtbl.end()) {
                    if (hashtbl[tmp1] != tmp2) return false;
                } else if (hashtbl.find(tmp2) != hashtbl.end()) {
                    if (hashtbl[tmp2] != tmp1) return false;
                } else {
                    hashtbl[tmp1] = tmp2;
                    hashtbl[tmp2] = tmp1;
                }
                tmp1.pop_back();
                tmp2.pop_back();
            }
            return true;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.