Vasya and String
High school student Vasya got a string of length n as a birthday present. This string consists of letters ‘a’ and ‘b’ only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.
Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
题目大意:一个长为n的字符串,只由字符 a 和 b 构成,最多可以更改 k 次,问更改后连续的子串最长长度,要求子串的字符全部一样;
求的是连续子串最长长度,无形中和双指针联系在一起了,可以分两个部分进行,一个是改 a ,一个是改 b;
先说改 a ,如果区间 [l,r] 的 a 的个数大于 k ,显然 r 不能再往右走,l 要往右走直到 s[l]=a ,减去这个 a ,r 才可以继续往右走,明显的关系就出现了;
代码:
#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=100100;
const int M=2000100;
const LL mod=1e9+7;
int n,k,ans;
int main(){
cin>>n>>k;
string s;cin>>s;
int suma=0,sumb=0,l=0;
for(int r=0;r<s.length();r++){
if(s[r]=='a') suma++;
if(suma>k){
while(s[l]=='b') l++;
l++;//去掉a
suma--;
}
ans=max(r-l+1,ans);
}
l=0;
for(int r=0;r<s.length();r++){
if(s[r]=='b') sumb++;
if(sumb>k){
while(s[l]=='a') l++;
l++;//去掉b
sumb--;
}
ans=max(r-l+1,ans);
}
cout<<ans<<endl;
return 0;
}