leetcode340

Given a string, find the length of the longest substring T that contains at most k distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.
Example 2:
Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.

同向双指针。sliding window + count Map。O(n)
i, j分别指针窗口头尾,一起向右挪动。map记录着每个字符出现过的次数,map.size()就是当前有多少种字符。
1.当j没走到头就while循环。
2.j慢慢增加,给map更新加入当前j位置字符后的字符统计情况。
3.如果字符种类多出来了,右移i并减少map中的统计情况,直到把i移到让字符种类恢复正常。
4.每个稳态打一次擂台。

细节:
1.每次写while循环的时候注意有没有改变()里的条件。你好几次忘记j++了笨蛋。

实现:

class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        int ans = 0;
        if (s == null) {
            return ans;
        }
        
        Map<Character, Integer> counts = new HashMap<>();
        int i = 0, j = 0;
        while (j < s.length()) {
            char cj = s.charAt(j);
            counts.put(cj, counts.getOrDefault(cj, 0) + 1);
            while (counts.size() > k) {
                char ci = s.charAt(i++);
                if (counts.get(ci) == 1) {
                    counts.remove(ci);
                } else {
                    counts.put(ci, counts.get(ci) - 1);
                }
            }
            ans = Math.max(ans, j - i + 1);
            // P1: 别忘了动j,写完while后先写这行好了。
            j++;
        }
        return ans;
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/9668531.html