CF 877B Nikita and string

简介: CF 877B Nikita and string

B. Nikita and string

time limit per test2 seconds

memory limit per test256 megabytes

inputstandard input

outputstandard output

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?


Input

The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters “a” and “b”.


Output

Print a single integer — the maximum possible size of beautiful string Nikita can get.


Examples

inputCopy

abba

outputCopy

4

inputCopy

bab

outputCopy

2

Note

It the first sample the string is already beautiful.


In the second sample he needs to delete one of “b” to make it beautiful.


题解:前缀和优化

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
char str[maxn];
int sum1[maxn], sum2[maxn];
/*
*/
int main() {
  scanf("%s", str + 1);
  int n = strlen(str + 1);
  for (int i = 1; i <= n; i++) {
    sum1[i] = sum1[i - 1];
    sum2[i] = sum2[i - 1];
    if (str[i] == 'a') sum1[i]++;
    if (str[i] == 'b') sum2[i]++;
  }
  int ans = 0;
  int mm = n;
  for (int i = 0; i <= n; i++) {
    mm = min(mm, sum2[i] - sum1[i]);
    ans = max(ans, sum2[i] - sum1[i] - mm);
  }
  cout << ans + sum1[n]<< endl;
  return 0;
}
相关文章
|
18天前
|
Java API 索引
String详解
String详解
28 0
|
5天前
|
存储 缓存 安全
|
11天前
|
存储 JavaScript C语言
【C++】String -- 详解(上)
【C++】String -- 详解(上)
|
11天前
|
存储 编译器 C++
【C++】String -- 详解(下)
【C++】String -- 详解(下)
|
18天前
string的使用
string的使用
26 0
|
18天前
|
索引
String
String当中与获取相关的常用方法有: public int length():获取字符串当中含有的字符个数,拿到字符串长度。 public String concat(String str):将当前字符串和参数字符串拼接成为返回值新的字符串。 public char charAt(int index);获取指定索引位置的单个字符。(索引从0开始。) public int index0f(Stringstr):查找参数字符串在本字符串当中首次出现的索引位置,如果 没有返回-1值。
25 0
|
11月前
|
缓存 安全 Java
关于 String 那些不得不说的那些事
关于 String 那些不得不说的那些事
|
9月前
grep 查询 包含string1、string2和string3的行
您可以使用以下命令来查询包含多个字符串的行: ``` grep 'string1.*string2.*string3' filename ``` 其中,`string1`、`string2`和`string3`是您要过滤的字符串,`filename`是要查询的文件名。 上述命令使用正则表达式来匹配包含`string1`、`string2`和`string3`的行,并将结果输出。`.`表示匹配任意字符,`*`表示匹配前面的字符0次或多次。 您还可以使用`-E`选项来启用扩展正则表达式模式,以实现更复杂的匹配模式: ``` grep -E 'string1|string2|string3' f
104 0
string.gmatch
string.gmatch
155 0
|
缓存 安全 Java
String 为什么不可变 ?
String 为什么不可变 ?
String 为什么不可变 ?

热门文章

最新文章