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