甲级PAT 1093 Count PAT's (25 分)(活用递推)

1093 Count PAT's (25 分)

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 10​5​​ characters containing only PA, 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(P,A,T不需要连续)

解题思路

对于确定位置的A,所能组成PAT的数量为A左边P的数量和右边T的数量的乘积,

可以先从0到s.length()遍历字符串将位置i左边对应的P的数量用p[i]存储,

当s[i]为'P'时,p[i]=p[i-1]+1;否则p[i]=p[i-1];

这里要注意当i为0的时候,p[-1]非法,所以p[i]从1下标开始存储,上述修改为

当s[i]为'P'时,p[i+1]=p[i]+1;否则p[i+1]=p[i];

p的下标从1到s.length()

从s.length()-1到0遍历字符串将位置i右边对应的T的数量用t[i]存储,

这里是从后往前统计,所以是反过来的,

当s[i]为'T'时,t[i]=t[i+1]+1;否则t[i]=t[i+1];

t的下标为0到s.length()-1

然后对于每个位置的A计算p[i+1]*t[i]就是A所在该位置对应的PAT的数量

完整代码

#include
using namespace std;

int main(){
	int i,p[100010],t[100010],num=0;
	string s;
	cin>>s;
	int len=s.length();
	memset(p,0,sizeof(p));
	memset(t,0,sizeof(t));
	for(i=0;i=0;i--){
		if(s[i] == 'T') t[i]=t[i+1]+1;
		else t[i]=t[i+1];
	}
	for(i=0;i

 

你可能感兴趣的:(PAT甲级)