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”的个数,直接暴力肯定会超时,所以我们换个角度来思考这个问题:

对于一个确定的位置A来说,它形成PAT的个数等于它左边的P的个数乘以它右边的T的个数,因此我们设两个参数 countT和countP用来记录当前位置A的左边P以及右边T的个数。

#include<iostream>
#include<string>
#include<string.h>
using namespace std;
#define mod 1000000007

int main()
{
	string str;
	cin >> str;
	int countT = 0;   //统计字符T的个数
	int countP = 0;  //统计字符P的个数
	int sum = 0;       //统计子串PAT的个数
	for (int i = 0; i < str.length(); i++)
	{
		if (str[i] == 'T')
			countT++;
	}
	for (int i = 0; i < str.length(); i++)
	{
		if (str[i] == 'A')
			sum = (sum+countP*countT)%mod;
		else if (str[i] == 'P')
			countP++;
		else if (str[i] == 'T')
			countT--;
	}
	cout << sum << endl;
	return 0;
}
发布了119 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/lovecyr/article/details/105456407