PAT A1093 Count PAT's (25分)

题目链接https://pintia.cn/problem-sets/994805342720868352/problems/994805373582557184

题目描述
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.

输入
Each input file contains one test case. For each case, there is only one line giving a string of no more than 10^​5​ characters containing only P, A, or T.

输出
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.

样例输入
APPAPT

样例输出
2

代码

#include<stdio.h>
#include<string.h>

const int maxn = 100010;
const int mod = 1000000007;
char str[maxn];
int p[maxn] = {0};
int main() {
	scanf("%s", str);
	int len = strlen(str);
	for(int i = 0; i < len; i++) {
		if(i > 0)
			p[i] = p[i - 1];
		if(str[i] == 'P')
			p[i] ++;
	}
	int ans = 0, t = 0;
	for(int i = len -1; i >= 0; i--) {
		if(str[i] == 'T')
			t++;
		else if (str[i] == 'A')
			ans = (ans + p[i]  * t) % mod;
	}
	printf("%d\n", ans);
	return 0;
}

【注】:刚开始使用gets()输入字符串,出现编译错误: error: ‘gets’ was not declared in this scope gets(s)。这是因为PAT编译器现在不支持gets(),用scanf("%s", str)完美解决。

发布了148 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Rhao999/article/details/104152956