# \*340. Longest Substring with At Most K Distinct Characters

<https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/>

## solution

* 至多包含 K 个不同字符的最长子串

```python
from collections import Counter

class Solution:
    def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
        char_count = Counter()

        max_length = start_index = 0
        for i, char in enumerate(s):
            char_count[char] += 1

            while len(char_count) > k:
                char_count[s[start_index]] -= 1

                if char_count[s[start_index]] == 0:
                    del char_count[s[start_index]]

                start_index += 1

            max_length = max(max_length, i - start_index + 1)
        return max_length
```

时间复杂度：O(n)\
空间复杂度：O(k)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://longxingtan.gitbook.io/mle-interview/01_leetcode/01_two_pointers/340.-longest-substring-with-at-most-k-distinct-characters.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
