pat-1093 Count PAT's(25)(巧算字符串中pat的个数)

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

作者: CAO, Peng

单位: Google

时间限制: 150 ms

内存限制: 64 MB

代码长度限制: 16 KB

 1.要想到要计算pat的个数,就是对于每一个a,计算它左边的p的个数s1和右边的t的个数s2,对于以这个a为中心的pat的个数sum = s1 * s2,

2.那么明确了一点就只要找到每一个A的时候把两边的P和T的数量相乘,累加就好了。

3.第一次想的是用一个数组存放每一个位置前面的p的数量,让第二个循环逆序查找‘A’的时候,把之前查到的‘T’的数量与当前位置存的‘P’的数目相乘,感觉还是有点小麻烦,还是柳神的更加简洁~

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#define ll long long
using namespace std;


const int maxn = 1e5;
const int mod = 1000000007;
char a[maxn];
int main(){
    scanf("%s",a);
    int len = strlen(a);
    int left_p = 0;
    int right_t = 0;
    int ans = 0;
    
    for(int i = 0 ;i < len ;i ++)
    {
        if(a[i] == 'T')
            right_t ++;
    }
    for(int i = 0 ;i < len;i++)
    {
        if(a[i] == 'P')
            left_p ++;
        else if(a[i] == 'T')
            right_t --;
        else if(a[i] == 'A')
        {
            ans += left_p * right_t;
            ans %= mod;
        }
    }
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hzyhfxt/article/details/82385308