One day Nikita found the string containing letters "a" and "b" only.
Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".
Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?
The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b".
Print a single integer — the maximum possible size of beautiful string Nikita can get.
abba
4
bab
2
It the first sample the string is already beautiful.
In the second sample he needs to delete one of "b" to make it beautiful.
【题意】:给你一个只含a,b的字符串,可以不改顺序地删去(也可以不删)一些字符使得其变为beautiful string。求能得到的最长beautiful string。beautiful string定义:字符串被分成三段(可以有空),不改变顺序,第一段和第三段只含有a,第二段只含有b。如:aa...aa/bb...bb/aa...aa 。
【分析】:
1.sa[i]表示[0,i)区间中a的个数,相当于前缀和,然后你遍历i,j把区间分成[0,i)[i,j)[j,n)三部分,求最大值即可
2.A[l]+A[i]-A[j]+B[j]-B[i],l代表字符串长度,直接预处理,预处理一下前i位和后i位有多少个a,然后直接枚举划分的位置
3.sa[i]表示 前i项有多少个a,sb[i]表示 前i项有多少个b,然后暴力n方可以枚举两个边界
取第一段[1,i]中所有的a,取第二段(i,j]中所有的b,取第三段(j,n]中所有的a,sa[i]代表[1,i],sa[i]-sa[j]就是[1,i]-[1,j]就是(j,i]
4.O(n)思路相当于直接dp
a表示当前只有第一段时的最大长度
ab表示当前有两段时的最大长度
aba表示有三段时的最大长度,也就是当前的答案
【代码】:
#include<bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair typedef long long ll; const int mn=5e3+5; int n; char s[mn]; int sa[mn],sb[mn]; int main() { scanf("%s",s+1); n=strlen(s+1); for(int i=1; i<=n+1; i++) { sa[i]=sa[i-1]+(s[i]=='a');//前i项多少个a sb[i]=sb[i-1]+(s[i]=='b'); } int ans=0; for(int i=0; i<=n+1; i++) { for(int j=i; j<=n+1; j++) { ans=max(ans,sa[i]+sb[j]-sb[i]+sa[n]-sa[j]); } } printf("%d ",ans); return 0; }
#include<bits/stdc++.h> using namespace std; int main(void) { std::ios::sync_with_stdio(false); string s; cin>>s; int n=s.length(),i; int a=0,aba=0,ab=0; for(i=0;i<n;i++) { if(s[i]=='a') aba++,a++; if(s[i]=='b') ab++; aba=max(aba,ab); ab=max(ab,a); } cout<<aba; return 0; }