C++ Solution using map and set


  • 0
    Y

    set<char> is used for the condition "No two characters may map to the same character". If the key s[i] is not in the map but the value t[i] is already in the value set, return false;

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            
            if (s.length() == 1) {
                return true;
            }
            map<char, char> m;
            set<char> sc;
            for (int i=0; i<s.length(); i++) {
                if (m.find(s[i]) == m.end()) {
                    if (sc.find(t[i]) != sc.end()) {
                        return false;
                    }
                    m.insert(pair<char, char>(s[i], t[i]));
                    sc.insert(t[i]);
                }
                else {
                    if (m[s[i]] != t[i]) {
                        return false;
                    }
                }
            }
            return true;
            
        }
    };
    

Log in to reply
 

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