[LeetCode] Longest Substring with At Most K Distinct Characters

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
if(!k) return 0;
int res = 0, head = 0;
unordered_map<char, int> m;
for(int i = 0; i < s.size(); i++) {
m[s[i]] = i;
if(m.size() > k) {
int p(INT_MAX);
char c;
for(auto& e : m) {
if(e.second < p) {
p = e.second; c = e.first;
}
}
m.erase(c);
head = p + 1;
}
res = max(res, i - head + 1);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/29/PS/LeetCode/longest-substring-with-at-most-k-distinct-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.