[Leetcode] 424. Longest Repeating Character Replacement 解题报告

题目

Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.

Note:
Both the string's length and k will not exceed 104.

Example 1:

Input:
s = "ABAB", k = 2

Output:
4

Explanation:
Replace the two 'A's with two 'B's or vice versa.

Example 2:

Input:
s = "AABABBA", k = 1

Output:
4

Explanation:
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.

思路

这道题目最简单的思路就是用移动窗口来解决。对于一个长度为m的子串而言,我们假设里面出现次数最多的字符的出现次数是n,那么m可以在k次之内被替换成为单一字符的充要条件是m - n <= k。因此,我们仅需要维护一个滑动窗口,使得这个窗口的长度减去出现次数最多的字符的出现次数小于等于k。在遍历的过程中找到这个最长的m即可。

我们下面实现的算法的空间复杂度是O(1),时间复杂度是O(n),这里n是输入字符串的长度。为什么for循环里面的while循环不额外增加时间复杂度呢?这是因为每个字符在while循环内最多被去除一次,因此while总的循环次数不会超过O(n)。

代码

class Solution {
public:
    int characterReplacement(string s, int k) {
        int size = s.size();
        vector<int> count(26,0);
        int begin = 0, maxlen = 0, ans = 0;
        for(int end = 0; end < size; ++end) {
            maxlen = max(maxlen, ++count[s[end] - 'A']);    // s[end] is the new possible dominate character
            while(end - begin + 1 - maxlen > k) {           // length(substring) - maxlen > k mean we cannot form repeating letters
                --count[s[begin++] - 'A'];
            }
            ans = max(ans,  end - begin + 1);
        }
        return ans;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值