原题地址:https://ac.nowcoder.com/acm/contest/3002/H
解题思路
比较两种情况(从1变成0,从0变成1)的最大长度,运用双指针(尺取法)
AC代码
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 200000 + 10;
int n, k;
char str[maxn];
char temp[] = "10";
int solve(char a,char a1)
{//从a变成a1
int res = 0;
int l = 0,r = 0,change = 0;
for(int i = 0;i<n;i++)
{
if(str[i]==a)
{
if(change<k)
{
change++;
r++;
}
else
{
while(l<=r&&str[l]!=a) l++;
l++;
r++;
}
}
else r++;
res = max(res,r-l);//r的起始值为1,故不用r-l+1.
}
return res;
}
int main()
{
scanf("%d%d", &n, &k);
scanf("%s", str);
int ans = max(solve('1','0'),solve('0','1'));
cout << ans;
return 0;
}