340. Longest Substring with At Most K Distinct Characters
Given a string, find the length of the longest substring T that contains at most k distinct characters.
For example, Given s = “eceba”
and k = 2,
T is "ece" which its length is 3
class Solution { public: int lengthOfLongestSubstringKDistinct(string s, int k) { if(s.empty()||k==0) return 0; unordered_map<char,int> mp; int left = 0,right = 0; int disticnt = 0; int res = INT_MIN; while(right<s.size()) { if(mp[s[right]]==0) disticnt++; mp[s[right]]++; while(disticnt>k) { mp[s[left]]--; if(mp[s[left]]==0) disticnt--; left++; } res = max(res,right-left+1); right++; } return res; } };