> For the complete documentation index, see [llms.txt](https://zhongwen.gitbook.io/leetcode-report/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zhongwen.gitbook.io/leetcode-report/medium/340.-longest-substring-with-at-most-k-distinct-characters.md).

# 340. Longest Substring with At Most K Distinct Characters

Given a string `s` and an integer `k`, return *the length of the longest substring of* `s` *that contains at most* `k` ***distinct** characters*.

&#x20;

**Example 1:**

```
Input: s = "eceba", k = 2
Output: 3
Explanation: The substring is "ece" with length 3.
```

**Example 2:**

```
Input: s = "aa", k = 1
Output: 2
Explanation: The substring is "aa" with length 2.
```

&#x20;

**Constraints:**

* `1 <= s.length <= 5 * 104`
* `0 <= k <= 50`

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