My very simple c++ solution, with 24ms, in 10 lines, using a map and a set, is waiting for your ups.


  • -1
    Z
    bool isIsomorphic(string s, string t) 
    {
        unordered_map<char,int> map1;
        unordered_set<char> set2;
        for(int i=0,n=s.size();;i++)
        {
            while(i<n && map1.find(s[i])==map1.end())
            {
                if(set2.find(t[i])!=set2.end()) return false;
                set2.insert(t[i]);
                map1[s[i]]=i++;
            }
            if(i==n) return true;
            if(t[i]!=t[map1[s[i]]]) return false;
        }
    }

  • 0
    T

    A very simple c++ solution, with 8ms, in 11 lines, using no spacial container.

    bool isIsomorphic(string s, string t) {
            if(s.size()!=t.size()) return false;
            char mp1[256],mp2[256];
            memset(mp1,0,256);
            memset(mp2,0,256);
            for(unsigned int i=0;i<s.size();++i)
            {
                if((mp1[static_cast<int> (s[i])]!=0 && mp1[static_cast<int> (s[i])]!=t[i])||
                    (mp2[static_cast<int> (t[i])]!=0 && mp2[static_cast<int> (t[i])]!=s[i]))
                return false;
                mp1[static_cast<int>(s[i])]=t[i];
                mp2[static_cast<int>(t[i])]=s[i];
            }
            return true;
    }

Log in to reply
 

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