C++ unordered_map solution


  • 0
    M
    class Solution {
    public:
        int lengthOfLongestSubstringKDistinct(string s, int k) {
            unordered_map<char, int>m;
            int count = 0;
            int result = 0;
            for(int i=0;i<s.length();i++){
                m[s[i]]++;
                while(m.size()>k){
                    m[s[count]]--;
                    if(m[s[count]] == 0)
                        m.erase(s[count]);
                    count++;
                }
                result = max(result, i-count+1);
            }
            return result;
        }
    };

Log in to reply
 

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