My Java solution with hashmap


  • 2
    H
    public int lengthOfLongestSubstring(String s) {
        int i = 0;
        int j = 0;
        int max = 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        while(j < s.length()) {
            char c = s.charAt(j);
            Integer index = map.get(c);
            if(index != null && index >= i) {
                if(j - i > max) {
                    max = j - i;
                }
                i = index + 1;
            }
            map.put(c, j);
            j++;
        }
        if(j - i > max) {
            max = j - i;
        }
        return max;
    }
    

    Try to reduce calling hashmap's functions.


Log in to reply
 

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