【LeetCode】424. Longest Repeating Character Replacement滑动窗口算法

【LeetCode】424. Longest Repeating Character Replacement滑动窗口

Given a string s that consists of only uppercase English letters, you can perform at most k operations on that string.

In one operation, you can choose any character of the string and change it to any other uppercase English character.

Find the length of the longest sub-string containing all repeating letters you can get after performing the above operations.

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

给出一个包含全为大写英文字母的Sring,通过k个步骤(每个步骤可将String中的任意位置的字符变为其他任意字母)将该String转变为拥有最长重复字母的String,最后返回该最长重复字母String的长度。

思路:

一看题型就知道是滑动窗口了,最简单的方法两个for循环遍历,但这样的O(n^2)效率显然不高。
下面的代码是LeetCode大神总结出来,记录一下:

题目所关注的是最长且"有效"的子字符串,所以滑动窗口的范围根本没必要缩小。每次循环要不就在窗口最右边增加一个字符的位置,要不就将整个窗口向右移动

public int characterReplacement(String s, int k){
	int[] count = new int[128];
    int max=0;
    int start=0;
    for(int end=0; end<s.length(); end++)
    {
        max = Math.max(max, ++count[s.charAt(end)]);
        if(max+k<=end-start)
            count[s.charAt(start++)]--;
    }
    return s.length()-start;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值