---
# System prepended metadata

title: 0340. Longest Substring with At Most K Distinct Characters
tags: [Leetcode, FaceBook, Sliding Window, Medium]

---

# 0340. Longest Substring with At Most K Distinct Characters
###### tags: `Leetcode` `Medium` `FaceBook` `Sliding Window`
Link: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
## 思路
直接按照[Sliding Window模板](https://leetcode-cn.com/problems/max-consecutive-ones-iii/solution/fen-xiang-hua-dong-chuang-kou-mo-ban-mia-f76z/)写就可以了~
## Code
```java=
class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        Map<Character,Integer> map = new HashMap<>();
        int l = 0;
        int r = 0;
        int res = 0;
        int cnt = 0;
        while(r<s.length()){
            if(!map.containsKey(s.charAt(r))){
                cnt++;
            }
            map.put(s.charAt(r),map.getOrDefault(s.charAt(r),0)+1);
            while(cnt > k){
                if(map.get(s.charAt(l))==1){
                    cnt--;
                    map.remove(s.charAt(l));
                }
                else{
                    map.put(s.charAt(l),map.get(s.charAt(l))-1);
                }
                l++;
            }
            res = Math.max(res, r-l+1);
            r++;
        }
        return res;
    }
}
```