C++ slide window one pass


  • 1
    B
    class Solution {
    public:
        int lengthOfLongestSubstringKDistinct(string s, int k) {
            unordered_map<char,int>pool;
            int left = 0, right = 0, ans = 0, len = s.length();
            while(right < len)
            {
                pool[s[right]]++;
                while(pool.size() > k)
                {
                    pool[s[left]]--;
                    if(pool[s[left]] == 0) pool.erase(s[left]);
                    left++;
                }
                int cur = 0;
                for(auto e : pool) cur += e.second;
                ans = max(ans, cur);
                right++;
            }
            return ans;
        }
    };

  • 0
    P

    @beetlecamera After check all the C++ solutions, yours is the best one , since it is fast and readable. Thanks !


Log in to reply
 

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