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

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

#include<iostream>
using namespace std;
int main(){
    string s;
    getline(cin,s);
   /*  用long long int 防止sum过大,p[]数组中p[i]表示下标为i的A前面有p[i]个P。
    sp为目前的P的数量,st表示目前T的数量 */
    long long int p[s.size()]={0},sp=0,st=0,sum=0; 
  /* 先正着遍历一遍用sp记录目前碰到P的数量,一旦遇到A
    就把当前P的数量储存到p[i]中,这样每个A前的P的数量就知道了*/
    for(int i=0;i<s.size();i++){ 
        if(s[i]=='P')
           sp++;
        if(s[i]=='A')
           p[i]=sp; 
    } 
  /* 再倒着遍历一遍,用st记录碰到的 T的数量,当遇到A时
     就把p[i](即A前P的数量)乘以st(即该A后的T的数量)加到sum上*/
    for(int i=s.size()-1;i>=0;i--){ 
        if(s[i]=='T')
           st++;
        if(s[i]=='A')
           sum+=st*p[i];
    }
    cout<<sum%1000000007<<endl;
    return 0;
} 

原文地址:https://www.cnblogs.com/A-Little-Nut/p/8416525.html