10 - line java code, clear and easy to understand


  • 0
    P
        public int lengthOfLongestSubstringTwoDistinct(String s) {
            int n = s.length(), start = 0, max = 0;
            Map<Character, Integer> map = new HashMap<>();        
            for (int i = 0; i < n; ++i) {
                map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
                max = Math.max(max, i - start);
                for ( ; map.size() > 2; ++start)
                    if (!map.remove(s.charAt(start), 1)) 
                        map.put(s.charAt(start), map.get(s.charAt(start)) - 1);                    
            }
            return Math.max(max, n - start);
        }
    

Log in to reply
 

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