PAT (Advanced Level) Practice 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 1 0 5 {10^5} 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的个数
②从末尾向首部统计T的累计个数,并寻找A
③每当找到A的时候,就将当前位置的累计P个数乘上累计T个数

代码

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1e7;
int main()
{
    
    
	string s;
	cin >> s;
	int sum = 0;
	
	int np[s.length()];
	int nt[s.length()];
	
	if(s[0] == 'P')
		np[0] = 1;
	else 
		np[0] = 0;
		
	for(int i = 1;i < s.length();i++)
	{
    
    
		if(s[i] == 'P')
			np[i] = np[i-1] + 1;
		else
			np[i] = np[i-1];
	}
	
	if(s[s.length()-1] == 'T')
		nt[s.length()-1] = 1;
	else 
		nt[s.length()-1] = 0;

	for(int i = s.length() - 2;i >= 0;i--)
	{
    
    
		nt[i] = nt[i+1];
		if(s[i] == 'A')
		{
    
    
			sum = (sum + np[i]*nt[i]) % 1000000007;
		}
		else if(s[i] == 'T')
		{
    
    
			nt[i] = nt[i+1] + 1;
		}
	}
	cout << sum;
}

猜你喜欢

转载自blog.csdn.net/weixin_43820008/article/details/114261399