Longest Substring with At most K Distinct Characters

// Given a string, find the length of the longest substring T that contains at most k distinct characters.

// For example, Given s = "eceba" and k = 2,

// T is "ece" which its length is 3.

public class LongestSubstringWithAtMostKDistinctCharacters {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        int res = 0, left = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            map.put(c, map.getOrDefault(c, 0) + 1);
            while (map.size() > k) {
                char l = s.charAt(left);
                map.put(l, map.get(l) - 1);
                if (map.get(l) == 0) map.remove(l);
                left++;
            }
            res = Math.max(res, i - left + 1);
        }
        return res;
    }
}

No comments:

Post a Comment