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.

Tips:

和上题一毛一样,把2换成k就行。

Code:

public class Solution {
    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);
            if (!map.containsKey(s.charAt(i))) map.put(c, 0);
            map.put(c, map.get(c) + 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;
    }
}

results matching ""

    No results matching ""