【PAT】(B)1040 有几个PAT

『题目』


字符串APPAPT中包含了两个单词“PAT”,其中第一个PAT是第2位(P),第4位(A),第6位(T);第二个PAT是第3位(P),第4位(A),第6位(T)。

现给定字符串,问一共可以形成多少个PAT?

输入格式:

输入只有一行,包含一个字符串,长度不超过10^5^,只包含P、A、T三种字母。

输出格式:

在一行中输出给定字符串中包含多少个PAT。由于结果可能比较大,只输出对1000000007取余数的结果。

输入样例:

APPAPT

输出样例:

2

『思路』


开始的思路 找出第一个“P”和第一个“A”中间“P”的个数p_cnt ,第一个“A”和第一个“T”中间“A”的个数a_cnt,第一个“T”到最后“T”的个数 t_cnt    ans = p_cnt * a_cnt * t_cnt,但是忽略了“PATPAT”这种存在重复的问题,如果多次判断会存在超时的问题。

所以采用以下思路:

从字符串最后开始遍历,如果是“T”,记录。如果是“A”,记录”AT“的个数。如果是“P”,则记录“PAT”的个数。

『第一次代码』

#include <iostream>
#include <string>
using namespace std;
int main() {
	string s;
	cin>>s;
	int p_index,a_index,t_index,len = s.length();
	int p_cnt = 0,a_cnt = 0, t_cnt = 0;
	if(s.find_first_of('P') != string::npos) {
		p_index = s.find_first_of('P');
		cout<<p_index<<"= p_index\n";
		if( s.find_first_of('A',p_index) != string::npos) {
			a_index = s.find_first_of('A',p_index);
			cout<<a_index<<"= a_index\n";
			if(s.find_first_of('T',a_index) != string::npos) {
				t_index = s.find_first_of('T',a_index);
				cout<<t_index<<"= t_index\n";
				for(int i = p_index; i < a_index; i++)
					if(s[i] == 'P')
						p_cnt++;
				cout<<"p_cnt = "<<p_cnt<<"\n";
				for(int i = a_index; i < t_index; i++)
					if(s[i] == 'A')
						a_cnt++;
				cout<<"a_cnt = "<<a_cnt<<"\n";
				for(int i = t_index; i < len; i++)
					if(s[i] == 'T')
						t_cnt++;
				cout<<"t_cnt = "<<t_cnt<<"\n";
			    }
			}
		}
		int ans = p_cnt * a_cnt * t_cnt;
		ans %= 1000000007;
		cout<<ans;
		return 0;
	}

 『AC代码』

#include <iostream>
#include <string>
using namespace std;
int main() {
	string s;
	cin>>s;
	int len = s.length();
	int pat_cnt = 0,at_cnt = 0, t_cnt = 0;
	for(int i = len - 1; i >=0; i--){
		if(s[i] == 'T')//如果是T,则记录T的个数
			t_cnt++;
		else if(s[i] == 'A')
			at_cnt = (at_cnt + t_cnt) % 1000000007;//如果是A,则计算AT的个数 
		else
			pat_cnt = (pat_cnt + at_cnt) % 1000000007;//如果是P,则计算PAT的个数 
	}
		cout<<pat_cnt;
		return 0;
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值