【PAT】1093. Count PAT's (25)

本文介绍了一种算法,用于计算字符串中特定子串“PAT”的出现次数。通过预先计算每个字符左侧的P和右侧的T的数量,高效地找出所有可能的组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

分析:以字母A为核心,计算在这个A左边的字母P的个数以及在这个A的右边的字母T的个数,两者相乘即以这个A为核心可以组建的PAT组合的个数。对每个A进行以上操作,结果相加即可。

#include <iostream>
#include <vector>
#include <string>
using namespace std;

struct node{
	node(int p, int t){
		numP = p;
		numT = t;
	}
	int numP;//在这个字母A左边的P的个数 
	int numT;//在这个字母A右边的T的个数 
};

int main(int argc, char** argv) {
	string str;
	cin>>str;
	int i;
	vector<node> vecA;
	int cntP=0, cntA=0, cntT=0;
	for(i=0; i<str.size(); i++){
	 	if(str[i]== 'P'){
	 		cntP++;	
		}else if(str[i]=='A'){
			vecA.push_back( node(cntP,0));
		}
	}	
	int index = vecA.size()-1;
	for(i=str.size()-1; i>=0; i--){
		if(str[i]=='T'){
			cntT++;
		}else if(str[i]=='A'){
			vecA[index--].numT = cntT;
		}		
	}
	long long  total = 0, t=1000000007;
	
	for(i=0; i<vecA.size(); i++){
		total = (total+vecA[i].numP*vecA[i].numT)%t;
	}
  	printf("%lld\n",total);
	return 0;
}


同样的思路,另一种写法:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main(int argc, char** argv) {
	string str;
	cin>>str;
	int len = str.size();
	vector<int> cntP(len);
	vector<int> cntT(len);
	int i;
	if(str[0]=='P'){
		cntP[0] = 1;
	}else{
		cntP[0] = 0;
	}
	int tmp;
	for(i=1; i<len; i++){
		if(str[i] == 'P'){
			tmp = 1;
		}else{
			tmp = 0;
		}
		cntP[i] = cntP[i-1] + tmp;
	}
	if(str[len-1]=='T'){
		cntT[len-1] = 1;
	}else{
		cntT[len-1] = 0;
	}
	for(i=len-2; i>=0; i--){
		if(str[i]=='T'){
			tmp=1;
		}else{
			tmp=0;
		}
		cntT[i] = cntT[i+1] + tmp;
	}
	long total = 0;
	for(i=1; i<str.size()-1; i++){
		if(str[i] == 'A'){
			total += cntP[i-1]*cntT[i+1];
			total %= 1000000007;
		}
	}
	printf("%ld\n",total);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值