Leetcode 340 Solution
This article provides solution to leetcode question 340 (longest-substring-with-at-most-k-distinct-characters)
Access this page by simply typing in "lcs 340" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters
Solution
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
map<char, int> m;
int l = 0;
int max_len = 0;
for (int i = 0; i < s.size(); i++)
{
m[s[i]]++;
while (l <= i && m.size() > k)
{
auto ch = s[l++];
m[ch]--;
if (m[ch] == 0)
m.erase(ch);
}
max_len = max(max_len, i - l + 1);
}
return max_len;
}
};