Sliding Window Summary 1 (Leetcode 424, Leetcode 340)

这两道题很像。都可以用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;
    }

转载于:https://www.cnblogs.com/stepsma/p/6076025.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值