Easy Java solution 5ms


  • 8
    N

    The idea is almost the same with a Hashmap solution, which costs about 20ms. To speed up,1) replace Hashmap with an array, and the index is the int value of its asicii code. 2) use char array instead of string.

        int[] map = new int[128];
        int max = 0, j = 0;
        char[] str = s.toCharArray();
        int length = s.length();
    
        for(int i = 0; i < length; i++) {
            if(map[str[i]] > 0)
                j =  Math.max(j, map[str[i]]);
            map[str[i]] = i + 1;
            max = Math.max(max, i - j + 1);
        }
        return max;

Log in to reply
 

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