159. Longest Substring with At Most Two Distinct Characters(Sliding Window)

Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.

Example 1:

Input: "eceba"
Output: 3
Explanation: t is "ece" which its length is 3.
Example 2:

Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.

Solution

sliding window

Complexity

O(N) O(1)

Code

class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        if(s == null || s.length() == 0) return 0;
        int i = 0, j = 0;
        Map<Character, Integer> map = new HashMap<>();
        int res = 0;
        for(;j < s.length();j++){
        
            map.put(s.charAt(j), map.getOrDefault(s.charAt(j), 0) + 1);
            if(map.size() > 2){
                while(map.size() > 2){
                    map.put(s.charAt(i), map.get(s.charAt(i)) - 1);
                    map.remove(s.charAt(i), 0);
                    i++;
                }
            }
            res = Math.max(res, j - i  + 1);
        }
        return res;
    }
}