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 000containing 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 字符串,任意切除,使得字符串由三部分组成,1和3 部分 全部都是 a,2 部分全部都是b,(有的部分可以为空),让你求得切完的字符串
的最长长度为多少;
思路:任意删除字符,删除字符后的答案要和全部字符相关; 像这样一类的题一般都会用到 前缀和后缀。所以我们这道题也用前缀和后缀解决,以为1, 3 部分全部都是由a组成,2部分由 b组成,所以我们只需找每一个b之前之后有多少a就是,最后在枚举b的位置就行了,per[i] + (j-i+1) + suf[j]; j-i+1 是指i到j有多少个b;
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define Max 5500
char str[Max];
int pre[Max],suf[Max],pos[Max]; // 前缀,后缀,每个b的位置;
int main()
{
int i,j,n;
while(~scanf("%s",str))
{
n = strlen(str);
int num = 0;
for(i=0;i<n;i++)
{
if(str[i]=='b')
{
pre[i] = i - num; // 求前缀,每一个b前面有多少a;
pos[num++] = i; // 记录b的位置;
}
}
int num1 = 0;
for(i=n-1;i>=0;i--)
{
if(str[i]=='a')
num1++;
else if(str[i]=='b')
suf[i] = num1; // 求后缀;
}
if(num == 0)
{
printf("%d\n",n);
continue;
}
int Ma = -INF;
for(i=0;i<num;i++) // 枚举每个b与b的区间
{
for(j = i;j<num;j++)
{
int k = pos[i],t = pos[j];
Ma = max(Ma,pre[k]+(j-i+1)+suf[t]);
}
}
printf("%d\n",Ma);
}
return 0;
}