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;
}
相关文章
|
3月前
|
Java API 索引
|
3月前
|
存储 JavaScript C语言
【C++】String -- 详解(上)
【C++】String -- 详解(上)
|
3月前
|
存储 编译器 C++
【C++】String -- 详解(下)
【C++】String -- 详解(下)
|
3月前
string的使用
string的使用
36 0
|
3月前
|
算法 Linux C语言
【c++】string
【c++】string
36 1
|
11月前
grep 查询 包含string1、string2和string3的行
您可以使用以下命令来查询包含多个字符串的行: ``` grep 'string1.*string2.*string3' filename ``` 其中,`string1`、`string2`和`string3`是您要过滤的字符串,`filename`是要查询的文件名。 上述命令使用正则表达式来匹配包含`string1`、`string2`和`string3`的行,并将结果输出。`.`表示匹配任意字符,`*`表示匹配前面的字符0次或多次。 您还可以使用`-E`选项来启用扩展正则表达式模式,以实现更复杂的匹配模式: ``` grep -E 'string1|string2|string3' f
142 0
「JDK」解析 String str=““与 new String()
一、基础概念 为了讲清楚他们的差异,这里先介绍几个概念。 1.1 常量池 所谓常量池:顾名思义就是用来存放一些常量的。该常量是在编译期被确定,并被保存在已编译的.class文件中,其中包括了类,方法,接口等包含的数值常量,字符常量和字符串常量。
string.gmatch
string.gmatch
166 0
|
缓存 安全 Java
String 为什么不可变 ?
String 为什么不可变 ?
String 为什么不可变 ?
|
存储 缓存 安全
为什么 String 是不可变的?
我最喜欢的 Java 面试问题,不好回答,但同时也非常有用。一些面试者也常问这个问题,为什么 String 在 Java 中是 final 的。 字符串在 Java 中是不可变的,因为 String 对象缓存在 String 池中。由于缓存的字符串在多个客户之间共享,因此始终存在风险,其中一个客户的操作会影响所有其他客户。
122 0
为什么 String 是不可变的?