【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;