Java 3ms beats 99.25%


  • 22
    J

    Since all the test cases use ASCII characters, you can use small arrays as a lookup tables.

    public class Solution {
        
        public boolean isIsomorphic(String sString, String tString) {
    
            char[] s = sString.toCharArray();
            char[] t = tString.toCharArray();
    
            int length = s.length;
            if(length != t.length) return false;
    
            char[] sm = new char[256];
            char[] tm = new char[256];
    
            for(int i=0; i<length; i++){
                char sc = s[i];
                char tc = t[i];
                if(sm[sc] == 0 && tm[tc] == 0){
                    sm[sc] = tc;
                    tm[tc] = sc;
                }else{
                    if(sm[sc] != tc || tm[tc] != sc){
                        return false;
                    }
                }
            }
            return true;
        }
    }

  • 5
    J

    great solution, so it uses the arrays to minic two hash table, but more efficient than hash table.


  • 0
    A

    can someone explain me this solution???


  • 0
    E

    if(sm[sc] == 0 && tm[tc] == 0)

    Is it actually correct to compare with 0 here? 0 can also be a valid char(first char), right?


  • 0
    L

    @eric108 The array sm[] and tm[] is the hash map. if sm[sc] == 0, then there is no key sc in the map. Since when you create the array sm[],the value is assigned to 0. With sm[sc] = tc, we say that sc is the key and tc is the value.


Log in to reply
 

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