8ms C++ solution


  • 0
    L
    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            int tab1[128], tab2[128];
            memset(tab1, 0xff, 128*sizeof(int));
            memset(tab2, 0xff, 128*sizeof(int));
            for (int i = 0; i < s.size(); ++i) {
                int a = s[i], b = t[i];
                if (tab1[a] == -1 && tab2[b] == -1) {
                    tab1[a] = b; tab2[b] = a;
                } else if (tab1[a] != -1 && tab2[b] != -1) {
                    if (tab1[a] != b || tab2[b] != a) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
            return true;
        }
    };

  • 0
    V

    For returning false you can write it in one single condition:

            if (tab1[a] == -1 && tab2[b] == -1) {
                tab1[a] = b; tab2[b] = a;
            } else if (tab1[a] == -1 || tab2[b] == -1 || tab1[a] != b || tab2[b] != a) 
                    return false;
    

Log in to reply
 

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