Givena string that consists of only uppercase English letters, you can replace anyletter in the string with another letter at most ktimes.Find the length of a longest substring containing all repeating letters you canget after performing the above operations.
Note:
Both the string's length and k will not exceed 104.
Example1:
Input:
s = "ABAB", k = 2
Output:
4
Explanation:
Replace the two 'A's with two 'B's or vice versa.
Example2:
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 repeatingletters, which is 4.
这是一道循环剪枝题
这一题给你一个字符串,这个字符串里面可能有相同的大写字符,然后给你一个k,你最多可以改变原字符串里面的k个字符,问你这样改变之后可以得到的最长的相同子串是什么
题目可能有点绕口,经过分析我们可以得到以下结论‘
1. 当字符串长度<=k,的时候,结果为字符串长度
2. 给定坐标left,right,原字符串从left到right之间的子串可以在最多K次变换里全部字符相等的条件是,假设sub是left到right之间的子串出现次数最多的字符,
要求right-left+1-count(sub)<=k
因此我们可以使用两层for循环遍历s的所有子串,需要注意的是,这里存在剪枝操作
当出现right-left+1-count(sub)>k的时候,right不用继续向后遍历,
这里还需要注意一点,每一次循环子串全部字符出现次数的统计个数都需要在前一次循环的统计值的基础上得到,不能重新统计,因为这样会超时
class Solution {
public:
int characterReplacement(string s, int k) {
if(s.size()<=k) return s.size();
vector<int> A(27,0);
vector<int> B;
int theMaxL=k;
for(int i=0;i<s.size()-k;i++)
{
if( i == 0)
{
for(int j=0;j<k;j++)
{
A[s[j]-'A'+1]++;
A[0] = max(A[s[j]-'A'+1],A[0]);
}
}
else
{
A[s[i-1]-'A'+1]--;
A[s[i+k-1]-'A'+1]++;
A[0]=0;
for(int j=1;j<=26;j++)
A[0] = max(A[0],A[j]);
}
B=A;
for(int j=i+k;j<s.size();j++)
{
B[s[j]-'A'+1]++;
B[0] = max(B[0],B[s[j]-'A'+1]);
if(j-i+1-B[0]>k) break;
else
{
theMaxL = max(theMaxL,j-i+1);
}
}
}
return theMaxL;
}
};