这两道题很像。都可以用Sliding Window来解。

Leetcode 424:

Longest Repeating Character Replacement 要求仅换K次,变成最长同样字符的continuous string,而optimal转换条件是

用string的长度 - 最多字符出现个数 (假设K没有限制)。由于K有限制,我们要用sliding window,来找到K可以实现的最大范围。注意,while中间那段更新max_cnt,没有也可以。

int characterReplacement(string s, int k) {
        if(s.empty()) return 0;
        unordered_map<char, int> mp;
        int res = 0, max_cnt = 0;
        int start = 0;
        for(int i=0; i<s.length(); i++){
            mp[s[i]]++;
            max_cnt = max(max_cnt, mp[s[i]]);
            while(i-start+1-max_cnt > k){
                mp[s[start]]--;
                for(auto it : mp){
                    if(it.second > max_cnt){
                        max_cnt = it.second;
                    }
                }
                start++;
            }
            res = max(res, i-start+1);
        }
        return res;
    }

Leetcode 340

这道题也是sliding window,而要点是可以用map的size来track究竟多少distinct charaters

int lengthOfLongestSubstringKDistinct(string s, int k) {
        if(s.empty()) return 0;
        unordered_map<char, int> mp;
        int max_len = 0, start = 0;
        for(int i=0; i<s.length(); i++){
            mp[s[i]]++;
            while(mp.size() > k){
                mp[s[start]]--;
                if(mp[s[start]] == 0){
                    mp.erase(s[start]);
                }
                start++;
            }
            max_len = max(max_len, i-start+1);
        }
        return max_len;
    }