PAT甲级刷题——1093有多少个PAT

题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805373582557184

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

题目大意:https://pintia.cn/problem-sets/994805260223102976/problems/994805282389999616  与乙级题一样

解题思路:直接暴力会超时!

       可以观察到“PAT”的个数与‘A’有关,每一个‘A'左边’P'的个数乘以‘A‘右边’T‘的个数再相加就是所求,所以只要求出左边’P‘的个数和右边’T‘的个数就可以了。

       建立一个数组p[ ]从左往右进行一次遍历,每一个p[i]继承上一个p[i-1],并且遇到’P‘时p[i]++,这样就将’A‘左边’P'的个数存到p[ ]数组中去了,右边求‘T’同理。为了更加简便,求‘T’的个数时不需要再用数组保存,直接用变量t存储,遇到‘T’时t++,在同一个循环中直接计算总个数sum,遇到’A‘时,计算t*p[i]这个’A‘对应的’PAT‘的个数,总个数为sum=(sum+t*p[i])%mod,因为题目要求,需要进行取余操作,mod为题目给出的数字。

代码如下:

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const  int mod=1000000007;
int main()
{
    string s;
    cin>>s;
    int n=s.size();//字符串长度
    int p[110000]={0};//记录左边P个数的数组
    for(int i=0;i<n;i++)//从左往右遍历
    {
        if(i>0)
        p[i]=p[i-1];//继承上一个结果
        if(s[i]=='P')
        {
            p[i]++;//等于p个数++
        }
    }
    int t=0;//记录右边T的个数
    int sum=0;//最终结果
    for(int i=n-1;i>=0;i--)//从右往左遍历
    {
        if(s[i]=='T')
        t++;//如果是T就++
        else if(s[i] == 'A')
        {
            sum=(sum+t*p[i])%mod;//如果是A,就计算结果并且取余
        }
    }
    cout<<sum<<endl;
    return 0;
}

 

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值