题目描述
The string APPAPT contains two PAT’s as substrings. The first one is formed by the 2nd, the 4th, and the 6th characters, and the second one is formed by the 3rd, the 4th, and the 6th characters.
Now given any string, you are supposed to tell the number of PAT’s contained in the string.
Input Specification:
Each input file contains one test case. For each case, there is only one line giving a string of no more than 105 characters containing only P, A, or T.
Output Specification:
For each test case, print in one line the number of PAT’s contained in the string. Since the result may be a huge number, you only have to output the result moded by 1000000007.
Sample Input:
APPAPT
Sample Output:
2
思路
对字符串进行遍历,如果是‘P’则‘P’的个数+1;如果是’A’,则这个‘A’可以与前面的p个‘P’,构成p个PA,因此‘PA’的个数+p;如果是‘T’,则这个‘T’可以与前面的pa个‘PA’构成pa个‘PAT’,则‘PAT’的个数+pa。注意为了防止溢出,在计算的过程中注意取余。
AC代码
#include <iostream>
using namespace std;
const int mod = 1000000007;
int main() {
char s[100010];
cin >> s;
int p = 0, pa = 0, pat = 0;
for (int i = 0; s[i]; i++) {
if (s[i] == 'P') p++;
else if (s[i] == 'A') pa = (pa + p) % mod;
else if (s[i] == 'T') pat = (pat + pa) % mod;
}
cout << pat << endl;
return 0;
}