题目描述
解题代码——参考labuladong
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
unordered_map<char, int> window;
int left = 0, right = 0;
int res = 0;
int cnt = 0;
while (right < s.size()) {
char c = s[right];
right ++ ;
if (window[c] == 0) cnt ++ ;
window[c] ++ ;
while (cnt > k) {
char d = s[left];
window[d] -- ;
if (window[d] == 0) cnt -- ;
left ++ ;
}
res = max(res, right - left);
}
return res;
}
};