Share my concise java solution. Using a hashmap assisted with two pointers.


  • 0
    N
    public int lengthOfLongestSubstring(String s) {
            int[] map = new int[256];
            int begin = 0, end = 0, counter = 0, d = 0;
    
            while (end < s.length()) {
                //大于0说明出现重复字符
                if (map[s.charAt(end++)]++ > 0) counter++;
                while (counter > 0) if (map[s.charAt(begin++)]-- > 1) counter--;
                d = Math.max(d, end - begin);
            }
    
            return d;
        }
    

Log in to reply
 

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