Very concise and easy-understand Java solution.


  • 0
    class Solution {
        public int lengthOfLongestSubstringTwoDistinct(String s) {
            if(s.length() <= 2) return s.length();
            HashMap<Character, Integer> map = new HashMap<>();  // map from char to its number of appearance.
            int low = 0, high = 1;
            map.put(s.charAt(low), 1);
            int maxLen = 0;
            while(high < s.length()) {
                map.put(s.charAt(high), map.getOrDefault(s.charAt(high), 0) + 1);
                while(map.size() > 2) {
                    if(map.get(s.charAt(low)) == 1) {
                        map.remove(s.charAt(low));
                    } else {
                        map.put(s.charAt(low), map.get(s.charAt(low)) - 1);
                    }
                    low++;
                }
                maxLen = Math.max(maxLen, high - low + 1);
                high++;
            }
            return maxLen;
        }
    }
    

Log in to reply
 

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