leetcode340 - Longest Substring with At Most K Distinct Characters - hard

Given a string, find the length of the longest substring T that contains at most k distinct characters.

Example 1:

Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.

Example 2:

Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.
 
Sliding window的思路,因为要找最长的,r要尽可能拓展,同时用hashmap统计经过的char2freq,hashmap里存的distinct chars多于k了再一点点往回缩l,直到把某一个char的计数全减完,把它从hasmap里彻底删了,r再继续拓展。
 
实现:
class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        
        int res = 0;
        
        unordered_map<char, int> mp;
        int l = 0, r = 0;
        while (r < s.size()){
            mp[s[r]]++;
            while (mp.size() > k){
                mp[s[l]]--;
                if (mp[s[l]] == 0)
                    mp.erase(s[l]);
                l++;
            }
            res = max(res, r-l+1);
            r++;
        }
        
        return res;
        
    }
};

 

 

posted @ 2020-08-06 07:35  little_veggie  阅读(82)  评论(0)    收藏  举报