PATA 1093 有几个PAT

这篇博客讨论了一道编程题,题目要求计算输入字符串中"PAT"子串的数量。关键在于理解每个"A"左边的"P"数量和右边的"T"数量的乘积之和。博客中提供了C++代码实现,强调了在累加过程中及时取模以避免整数溢出的问题。
摘要由CSDN通过智能技术生成

题目:
1093 Count PAT’s
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.

  1. 题目思路:“PAT”的数量即为每个"A"左边的“P”个数与右边的“T”个数的乘积之和。
  2. 易错点:取模应在每次累加时进行而非最后进行一次取模 ,否则会溢出。

题解:

#include <stdio.h>
#include <iostream>
#include <cstring>

const int MAX_N=100010;
const int MOD=1000000007;

int main(){
    char str[MAX_N];
    scanf("%s",str);
    int len = strlen(str);
    int P[len],T[len];//P记录该下标左边P的个数,T记录该下标右边T的个数
    int ans=0;
    int num_p=0,num_t=0;
    for(int i=0;i<len;i++){

        if(str[i]=='P') num_p++;//这个字母不加,后面的才加(这个顺序不会对结果造成影响)
        P[i]=num_p;

        if(str[len-i-1]=='T') num_t++;
        T[len-i-1]=num_t;
    }
    for(int j=0;j<len;j++){
        if(str[j]=='A')
            ans = (ans + P[j]*T[j])%MOD;//累计乘积时就应取模,否则int可能装不下
    }
    printf("%d\n",ans);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值