第一行两个整数 n , m (1<=m<=n<=50000),第二行为长度为n且只包含’a’和’b’的字符串s。
输出在操作次数不超过 m 的情况下,能够得到的 最大连续 全’a’子串或全’b’子串的长度。
8 1 aabaabaa
5
把第一个 'b' 或者第二个 'b' 置成 'a',可得到长度为 5 的全 'a' 子串。
#解析:https://blog.csdn.net/weixin_42001089/article/details/87114410 n,m = [int(e) for e in input().split()] Str = input() result = 0 a_count = 0 b_count = 0 q = [] for e in Str: if e=='a': a_count+=1 if e=='b': b_count+=1 if a_count>m and b_count>m: if e=='a': while True: if q[0]=='a': q.pop(0) break q.pop(0) b_count-=1 a_count-=1 else : while True: if q[0]=='b': q.pop(0) break q.pop(0) a_count-=1 b_count-=1 q.append(e) result = max(result,len(q)) print(result)
#include <iostream>#include <string>#include <algorithm>usingnamespacestd;intmain(){intn,m;while(cin>>n>>m){string str;cin>>str;if(n<=2*m+1)cout << n << endl;else{intl=0;inta=0,b=0;intright=0;for(inti=0; i<n-2*m-1; i++){if(i>0){if(str[i-1]=='a'){a--;}else{b--;}}for(intj=right; j<n; j++){if(str[j]=='a')a++;elseb++;if(j-i+1>2*m+1){if(a>m && b>m){if(j-i>l)l=j-i;right=j+1;break;}}}}cout << l << endl;}}return0;}
#include <iostream> #include <unordered_map> #include <algorithm> using namespace std; int main() { int n,m; //领扣424题 while (cin>>n>>m) { string s; cin>>s; unordered_map<char,int> map1; int start=0,end=0,max_freq=0,res=0; while (end < n) { map1[s[end]]++; max_freq = max(max_freq,map1[s[end]]); if (end-start+1-max_freq > m) { map1[s[start]]--; start++; } res = max(res,end-start+1); end++; } cout<<res<<endl; } }
#include <iostream> #include <vector> #include <queue> using namespace std; int main() { int n,m; cin>>n>>m; char c; string s; for(int i=0;i<n;++i) { cin>>c; s+=c; } // cout<<s<<endl; queue<int> que; int maxLen=0; int a_cnt=0,b_cnt=0; for(int i=0;i<s.size();++i) { // que.push(s[i]); if(s[i]=='a') ++a_cnt; if(s[i]=='b') ++b_cnt; if(a_cnt>m && b_cnt>m) { // maxLen=que.size()>maxLen?que.size():maxLen; if(s[i]=='a') { while(que.front()!='a') { que.pop(); --b_cnt; } que.pop(); --a_cnt; } else { while(que.front()!='b') { que.pop(); --a_cnt; } que.pop(); --b_cnt; } } que.push(s[i]); maxLen=que.size()>maxLen?que.size():maxLen; } cout<<maxLen<<endl; return 0; } /* 10 2 aabaabbbba */编译是通过的,但是如果是10,2 aabaabbbba。运行结果是6,不知道为什么编译会通过??