LeetCode "Longest Substring with At Most K Distinct Characters"

时间:2023-11-21 11:01:50

A simple variation to "Longest Substring with At Most Two Distinct Characters". A typical sliding window problem.

class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
unordered_map<char, unsigned> hm; int ret = , start = ;
for (int i = ; i < s.length(); i++)
{
hm[s[i]]++; if (hm.size() <= k)
{
ret = std::max(ret, i - start + );
}
else
{
while (start < i && hm.size() > k)
{
char nc = s[start];
if (hm[nc] == ) hm.erase(nc);
else hm[nc]--; start++;
}
}
}
return ret;
}
};