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 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

pat的数量就是每个a左边p的数量×右边t的数量,比如PPAAT,第一个A左边两个p,右边一个t,组成2个pat,第二个A也是,一共四个
一开始我遍历s,如果当前位为a,就遍历它前面,算有几个p,将几个p存在hashTablle对应的当前a的位置。但是这样时间复杂度就0(N^2)了,肯定超时了,所以换个思路,直接计算p的个数,如果当前位为a,直接将当前有几个p赋给对应的hashTable,这样每个a的位置存的都是左边有几个p
然后反向遍历,如果当前位为T,就累加t的个数,如果为a,就用sum +=当前a右边t的个数 * a左边p的个数

#include<iostream>
using namespace std;
typedef long long ll;
int main(){
    string s;
    cin>>s;
    ll sum = 0;
    int cntT = 0;
    int cntP = 0;
    int hashTable[100010] = {0};//记录每一位前的P有几个,然后反着遍历数每一个A后面有几个T即可
    for(int i = 0; i < s.length(); i++){
        if(s[i] == 'P'){
            cntP++;
        }
        if(s[i] == 'A'){
            hashTable[i] = cntP;
        }
    }
    for(int i = s.length() - 1; i >0; i--){
        if(s[i] == 'T'){
            cntT++;
        }
        else if(s[i] == 'A'){
            sum += cntT * hashTable[i];
        }
    }
    cout<<sum%1000000007;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值