340. Longest Substring with At Most K Distinct Characters
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
vector<int> cnt(256, 0);
int dis = 0, idx = 0, res = 0;
if (!k) return 0;
for (int i = 0; i < s.size(); i++) {
if (!cnt[s[i]]) {
while (dis >= k && idx < i) {
cnt[s[idx]]--;
dis -= cnt[s[idx++]] == 0;
}
dis++;
}
cnt[s[i]]++;
res = max(res, i - idx + 1);
}
return res;
}
};