8ms clean C++ solution


  • 1

    The main idea is to translate different strings to some number sequences. For example, "abcde" should be 12345, "foo" should be 122, "voodoo" should be 122322. As long as the generated numbers equal, different strings should be considered isomorphic strings.

    In the code, ss and tt are the two numbers at the same positions in string s and t, we simply compare them and we are done.

    bool isIsomorphic(string s, string t) {
        int stbl[128] = {0}, ttbl[128] = {0}, sidx = 0, tidx = 0, ss, tt;
        for( int i=0; i<s.size(); i++ ) {
            ss = stbl[s[i]] ? stbl[s[i]] : ( stbl[s[i]] = ++sidx );
            tt = ttbl[t[i]] ? ttbl[t[i]] : ( ttbl[t[i]] = ++tidx );
            if( ss != tt ) return false;
        }
        return true;
    }
    

    Update

    I just realized that I don't need to make "voodoo" "122322", "122422" will also do. So a little modification:

    bool isIsomorphic(string s, string t) {
        int stbl[128] = {0}, ttbl[128] = {0}, ss, tt;
        for( int i=0; i<s.size(); i++ ) {
            ss = stbl[s[i]] ? stbl[s[i]] : ( stbl[s[i]] = i+1 );
            tt = ttbl[t[i]] ? ttbl[t[i]] : ( ttbl[t[i]] = i+1 );
            if( ss != tt ) return false;
        }
        return true;
    }

Log in to reply
 

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