1. Description
Given an string only containing uppercase English letters, and an integer k, which represents you can replace any letter in the string
with another letter at most k times. Find the longest substring consists of same letters.
2. Solution
Slide Window.
What is sure is that the answer is at least k+1.
First, use a map to count the number of the first k+1 letters in the string.
Then, enter a loop, the loop start at the k+1 position in the string.
In one loop, add up the current letter to the map, and find whether the diff between the numbers of letters in the range and the numbers of the most common letter in the map
is less or equal to k.
If it's true, update the answer to the maximum of the original answer and the numbers of letters in the range.
Otherwise, move the left point to the right, until the range can be changed into string with same letters with at most k replacement.
3. Code
int characterReplacement(string s, int k) {
int n = s.size();
if(n<=k+1) return n;
map<char,int>m;
for(int i=0;i<k+1;i++){
m[s[i]]++;
}
int ans = k+1;
int left = 0;
for(int i=k+1;i<n;i++){
m[s[i]]++;
if(ok(m,k))
ans = max(ans,i-left+1);
else{
while(!ok(m,k)){
m[s[left]]--;
left++;
}
ans = max(ans,i-left+1);
}
}
return ans;
}
bool ok(map<char,int>m,int k){
int big = 0;
int sum = 0;
for(int i=0;i<26;i++){
sum+=m[i+'A'];
big = max(big,m[i+'A']);
}
int diff = sum-big;
if(diff<=k) return true;
else return false;
}