340. Longest Substring with At Most K Distinct Characters
https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/description/
Given a string, find the length of the longest substring T that contains at most k distinct characters.
For example, Given s = “eceba” and k = 2,
T is "ece" which its length is 3.
Thoughts
包含最多K个不同字符的最长子数组的长度。返回最长的连续子串的长度=>动态滑动窗口。内循环压缩滑动窗口(++l),使得滑动窗口在每次循环后满足题目要求,即最多K个不同的字符。用dict记录窗口各char出现的频率并统计独特元素个数,如果窗口内独特元素超过了k,则开始压缩窗口。
Code
Analysis
时间复杂度O(N).
Previous1248. Count Number of Nice SubarraysNext395. Longest Substring with At Least K Repeating Characters
Last updated
Was this helpful?