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.

这回我题看懂了,还是不会做,网上的答案说是用滑动窗口的思想来解决问题,也就是确定滑动窗口大小,默认窗口大小应该是要大于k的,然后通过统计起始位置中窗口中的字母的数量,得出数量最多的字母的值,然后如果窗口大小-字母数量值<=k,说明当前窗口符合条件,可以让窗口的右边界+1,再次重复上边的步骤,但是注意的是不需要再次遍历字符串来统计字母数量,只需要右边界的字母++就可以了,当窗口大小-字母数量值>k时,说明窗口大了,需要减少窗口的左边界,所以进行左边界+1,然后之前左边界的字母在统计数组中-1。具体代码实现如下:

int len=s.length();
	int[] carr=new int[128];
	int start=0,end=0;
	int maxCount=0;
	int maxLen=0;
	for(end=0;end<len;end++) //移动窗口的结束位置从零开始
	{
		char c=s.charAt(end); //首先先取出0的字母
		maxCount=Math.max(maxCount, ++carr[c]);//然后将字母存放到ASC码数组中,其中取字母重复数量最高的
		while(end-start+1-maxCount>k)//窗口大小减去最高出现的数字的次数大于k时,说明窗口大了,需要从左减小窗口
		{
			carr[s.charAt(start)]--;//将左起始位置的字母的计数减一
			start++;//起始位置++,起始位置增加意味着下次循环的窗口位置是从++后的位置开始的,因为之前的start——end都不满足,也就意味着start-end+1也不会满足条件
		}
		maxLen=Math.max(maxLen, end-start+1);//跳出来后选出和上次循环选出的比较,选出最大的
	}
return maxLen;

猜你喜欢

转载自blog.csdn.net/baidu_36094751/article/details/81080326