> For the complete documentation index, see [llms.txt](https://851958789.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://851958789.gitbook.io/notes/0340_longest_substring_with_at_most_k_distinct_characters/slt.md).

# Solution1 sliding window + hash table

* 时间复杂度 $O(n)$

  &#x20; n 是字符串长度
* 空间复杂度 $O(k)$

  &#x20; k 是不同字符的个数

基本思想是：在字符串上移动滑动窗口，保证窗口内有不超过 k 个不同字符，同时在每一步更新最大子串长度。

用哈希表来保证窗口中不超过 k 个不同的字符
