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
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
int res = 0;
unordered_map<char, int> freqs;
for (int l = 0, r = 0, cnt = 0; r < s.length(); ++r) {
const auto rk = s[r];
if (freqs[rk] == 0) ++cnt;
++freqs[rk];
while (cnt > k) {
const auto lk = s[l];
--freqs[lk];
++l;
if (freqs[lk] == 0) --cnt;
}
res = max(res, r - l + 1);
}
return res;
}
};Analysis
时间复杂度O(N).
Previous1248. Count Number of Nice SubarraysNext395. Longest Substring with At Least K Repeating Characters
Last updated
Was this helpful?