题目连接:Codeforces 385B Bear and Strings
题目大意:给出一个字符串,问说该字符串中有多少个子串包含“bear”。
解题思路:遍历,每次找到“bear”,就用该串前面个字符数x,以及该串后面的字符数y,ans += (x+1)*(y+1)- 前一个“bear”所在位置的字符串(重复的)
#include <stdio.h> #include <string.h> #include <iostream> using namespace std; typedef long long ll; const int N = 50005; int main() { char str[N]; scanf("%s", str); ll x = 0, len = strlen(str), ans = 0; for (ll i = 0; i < len - 3; i++) { if (str[i] == ‘b‘ && str[i+1] == ‘e‘ && str[i+2] == ‘a‘ && str[i+3] == ‘r‘) { ans += ((i + 1) * (len - i - 3) - x * (len - i - 3)); x = i + 1; } } cout << ans << endl; return 0; }
Codeforces 385B Bear and Strings(字符串)
原文:http://blog.csdn.net/keshuai19940722/article/details/18882463