有一个仅包含’a’和’b’两种字符的字符串s,长度为n,每次操作可以把一个字符做一次转换(把一个’a’设置为’b’,或者把一个’b’置成’a’);但是操作的次数有上限m,问在有限的操作数范围内,能够得到最大连续的相同字符的子串的长度是多少。
输入描述:
第一行两个整数 n , m (1<=m<=n<=50000),第二行为长度为n且只包含’a’和’b’的字符串s。
输出描述:
输出在操作次数不超过 m 的情况下,能够得到的 最大连续 全’a’子串或全’b’子串的长度。
示例1
输入:
8 1
aabaabaa
输出:
5
说明:
把第一个 ‘b’ 或者第二个 ‘b’ 置成 ‘a’,可得到长度为 5 的全 ‘a’ 子串。
#include <iostream>
#include <string>
using namespace std;
int GetLongStr(string str,int num,int count){
int res=-1;
int left=0,right=0;
int tmp1=0,tmp2=0;
for (right=0;right<str.size();right++){
if (str[right]=='a'){
tmp1++;
}else{
tmp2++;
}
if (tmp1>count && tmp2>count){
res=max(res,right-left);
if (str[left]=='a'){
tmp1--;
}else{
tmp2--;
}
left++;
}
}
return res;
}
int main(){
int num,count;
cin>>num>>count;
string str_in;
cin>>str_in;
cout<<GetLongStr(str_in,num,count);
return 0;
}```