1093 Count PAT’s (25 point(s))
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
题目大意
给定一个字符串,数一数其中包含多少个PAT,位置不同即视为不同PAT
解题思路
遍历字符串,每遇到一个字符A,就将它左边P的个数和右边T的个数相乘,并将结果累加至ans中。注意点是取余的写法
代码1
双数组,不够简洁
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstring>
const int maxn = 100010;
char str[maxn];
int cntP[maxn] = { 0 };
int cntT[maxn] = { 0 };
int main()
{
int ret = scanf("%s", str);
int len = strlen(str);
int ans = 0;
for (int i = 0; i < len; ++i) {
if (str[i] == 'P') cntP[i] = i > 0 ? cntP[i - 1] + 1 : 1;//如果是P,则继承上一个位置的值并加1
else if (i > 0) cntP[i] = cntP[i - 1];//如果不是P,则继承上一个位置的值
}
for (int i = len - 1; i >= 0; --i) {
if (str[i] == 'T') cntT[i] = i < len - 1 ? cntT[i + 1] + 1 : 1;//同上
else if (i < len - 1) {
cntT[i] = cntT[i + 1];
if (str[i] == 'A')
ans = (ans + cntP[i] * cntT[i]) % 1000000007;//不能写成ans += (cntP[i] * cntT[i]) % 1000000007
}
}
printf("%d", ans);
return 0;
}
代码2
参考的算法笔记,在遍历寻找右边T的值时,不存入数组,直接累加答案
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstring>
const int maxn = 100010;
char str[maxn];
int cntP[maxn] = { 0 };
int cntT[maxn] = { 0 };
int main()
{
int ret = scanf("%s", str);
int len = strlen(str);
int ans = 0, rightTNum = 0;
for (int i = 0; i < len; ++i) {
if (i > 0) cntP[i] = cntP[i - 1];
if (str[i] == 'P') ++cntP[i];
}
for (int i = len - 1; i >= 0; --i) {
if (str[i] == 'T') ++rightTNum;
if (str[i] == 'A') {
ans = (ans + cntP[i] * rightTNum) % 1000000007;
}
}
printf("%d", ans);
return 0;
}