这道题的代码是借鉴大佬的,写的很精简,大赞。
#include <cstdio> #include <cstring> #include <string> #include <cmath> #include <iostream> #include <algorithm> #include <vector> #include <stack> #include <sstream> #include <map> #include <set> #include <queue> #include <stdlib.h> typedef long long ll; using namespace std; string str; int n,k; int check(char a,char b) //a --> b(要转换成的字符) 0转1 ,或者 1转0 { int l = 0; int change = 0,ans = 0; for(int i = 0; i < n; ++i) //一共n次for循环 ,n为字符串的长度 { if(str[i] != b) //b是要转成的字符(不为b,表示可以转换) { if(change < k) //如果change小于变换的次数,表示仍然可以转换,change++ { change++; } else //如果转换的次数用完了,就跳到最左边的a的下一个(不管下一个是a还是b) { while(str[l] != a) l++; l++; } } ans = max(ans,i+1-l); //ans = ans 和 当前l-i之间的最大长度(i+1-l) 之中的最大值 } return ans; } int main() { cin >> n >> k; //01字符串的长度 、 可以转换的次数 cin >> str; //输入字符串 int ans = max(check('0','1'),check('1','0')); cout << ans << endl; return 0; }