C++ map solutions.


  • 0
    C
    bool isIsomorphic1(string s, string t) {
        map<char, char> myMap1, myMap2;
        string::iterator it1, it2;
        for (it1=s.begin(), it2=t.begin(); it1!=s.end(); it1++, it2++) {
            if (myMap1.find(*it1)==myMap1.end())
                myMap1[*it1] = *it2;
            else if (myMap1[*it1] != *it2)
                return false;
            if (myMap2.find(*it2)==myMap2.end())
                myMap2[*it2] = *it1;
            else if (myMap2[*it2] != *it1)
                return false;
        }
        return true;
    }
    
    bool isIsomorphic2(string s, string t) {
        unordered_map<char, char> myMap1, myMap2;
        string::iterator it1, it2;
        for (it1=s.begin(), it2=t.begin(); it1!=s.end(), it2!=t.end(); it1++, it2++) {
            if (myMap1.find(*it1)==myMap1.end())
                myMap1[*it1] = *it2;
            else if (myMap1[*it1] != *it2)
                return false;
            if (myMap2.find(*it2)==myMap2.end())
                myMap2[*it2] = *it1;
            else if (myMap2[*it2]!=*it1)
                return false;
        }
        return true;
    }
    
    bool isIsomorphic(string s, string t) {
        vector<char> v1(256, 0), v2(256, 0);
        for (int i=0; i < s.size(); i++) {
            if (!v1[s[i]] && !v2[t[i]]) {
                v1[s[i]] = t[i];
                v2[t[i]] = s[i];
            }
            else if (v1[s[i]]!=t[i] || v2[t[i]]!=s[i])
                return false;
        }
        return true;
    }

  • -1
    T

    bool isIsomorphic1(string s, string t) {
    map<char, char> myMap1, myMap2;
    string::iterator it1, it2;
    for (it1=s.begin(), it2=t.begin(); it1!=s.end(); it1++, it2++) {
    if (myMap1.find(*it1)==myMap1.end())
    myMap1[*it1] = *it2;
    else if (myMap1[*it1] != *it2)
    return false;
    if (myMap2.find(*it2)==myMap2.end())
    myMap2[*it2] = *it1;
    else if (myMap2[*it2] != *it1)
    return false;
    }
    return true;
    }


  • 0
    L

    Arrays are better than maps


Log in to reply
 

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