C++ Solution for Longest Substring with At most k Distinct Characters


  • 0
    G
    class Solution{//two pointers
    public:
        int lengthOfLongestSubstringKDistinct(string s, int k){
            unordered_map<char, int> mp;
            int result = 0;
            int index = 0;//the leftmost character
            for(int i=0;i<s.size();i++){
                mp[s[i]]++;
                while(mp.size()==k+1){
                    mp[s[index]]--;
                    if(mp[s[index]]==0) mp.erase(s[index]);
                    index++;
                }
                result = max( result, i-index+1);
            }
            return result;        
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.