B. Bear and Strings
来源:互联网 发布:淘宝一键复制在哪里 编辑:程序博客网 时间:2024/04/29 12:40
The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring.
String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r.
Help the bear cope with the given problem.
The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters.
Print a single number — the answer to the problem.
bearbtear
6
bearaabearc
20
In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9).
In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11).
解题说明:题目的意思是找到一个包含"bear"的子串,要求bear连续出现即可,对子串的首尾没有要求。假设字符串总长为n,如果找到了bear,起始位置为i(从0开始计算),那么一共有n-i-3个子串满足包含“bear”的条件。当然,如果后面还能找到连续的“bear”,那么为了和之前的区分,从第一次出现bear的e开始到第二次出现bear的b这个区间内都可以作为第二个包含bear的子串的起始位置。这样遍历下去即可,最后累加。
#include<iostream>#include<cstdio>#include<cmath>#include<cstdlib>#include <algorithm>#include<cstring>using namespace std;int main(){char s[5000];int i, j, k, n;long count = 0;char t;scanf("%s", &s);n = strlen(s);j = -1;for (i = 0; i<n - 3; i++){if (strncmp(s + i, "bear", 4) == 0){count += (i - j)*(n - i - 3);j = i;}}printf("%ld\n", count);return 0;}
- B. Bear and Strings
- CF 226 DIV2 B. Bear and Strings
- Codeforces 385B Bear and Strings
- Codeforces Round #226 (Div. 2) B. Bear and Strings
- Codeforces Round #226 (Div. 2)B. Bear and Strings
- Codeforces 385B Bear and Strings(字符串)
- Codeforces Round #226 (Div. 2)B. Bear and Strings
- CF 385B Bear and Strings 求子串个数
- 573B - Bear and Blocks
- B. Bear and Three Musketeers
- B. Bear and Finding Criminals
- B - Bear and Five Cards
- B. Mike and strings
- B. Mike and strings
- B. Mike and strings
- B. Mike and strings
- CodeForces 574B-Bear and Three Musketeers
- Codeforces 574B Bear and Three Musketeers
- java个人学习笔记04(function、overload、array、栈、堆)
- ios 动画详解
- 关于spring定时器的搭建
- 运行数据库遇到错误oracle not aviliable解决过程
- Fortran common
- B. Bear and Strings
- 在.net中悄悄执行dos命令,并获取执行的结果
- <item> tag requires a 'drawable' attribute or child tag defining a drawab
- 自定义横向ProgressBar样式圆角改直角
- lua随机数
- plsql连接数据库的方法
- IOS手势初步学习--监听相应的手势处理
- Oracle 10g RAC 客户端连接不稳定
- Ogre材质系统总结(一)