Two smiliar answer, one passed, another not


  • 0
    A

    (1) passed answer Reference

    '''

    public boolean isIsomorphic(String s, String t) {
    
        char[] maps = new char[128];
        char[] mapt = new char[128];
        for (int i = 0; i < s.length(); i++) {
            if (maps[s.charAt(i)] != mapt[t.charAt(i)]) {
            return false;
            }
            maps[s.charAt(i)] = mapt[t.charAt(i)]=(char)(i+1);
        }
        return true;
    

    }

    (2) not passed answer , stoped in test 28: "abcdefghijklmnopqrstuvw...." (a very long string)

    public boolean isIsomorphic(String s, String t) {
        Map<Character, Integer> maps = new HashMap<>();
    	Map<Character, Integer> mapt = new HashMap<>();
    	for (int i = 0; i < s.length(); ++i) {
    		Integer a = maps.get(s.charAt(i));
    		Integer b = mapt.get(t.charAt(i));
    
    		if (a != b) {
    			return false;
    		}
    
    		maps.put(s.charAt(i), i);
    		mapt.put(t.charAt(i), i);
    	}
    	return true;
    }
    

    I don't know why, some body can give me an explain, thankyou


  • 0
    H

    Hash tables have only an average constant time performance. The worst case behaviour is linear. It might perform better (or not) if you define an initial capacity of 128 to the HashMap.


Log in to reply
 

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