PAT-B 1040. 有幾個PAT(25)

傳送門

https://pintia.cn/problem-sets/994805260223102976/problems/994805282389999616

題目

字符串APPAPT中包含了兩個單詞“PAT”,其中第一個PAT是第2位(P),第4位(A),第6位(T);第二個PAT是第3位(P),第4位(A),第6位(T)。
現給定字符串,問一共可以形成多少個PAT?
輸入格式:
輸入只有一行,包含一個字符串,長度不超過10^5,只包含P、A、T三種字母。
輸出格式:
在一行中輸出給定字符串中包含多少個PAT。由于結果可能比較大,只輸出對1000000007取余數的結果。
輸入樣例:
APPAPT
輸出樣例:
2

分析

開始先是想了一個暴力算法結果超時了,最壞要計算10^3次,后來再參考了別人的代碼才學會了這個方法。
簡單來說就是:
從末尾開始遍歷
1.先找到T的個數;
2.再找到A的個數,每次找到后都把A后面的T的個數加上,作為AT的個數;
3.再找到P的個數,每次找到后都把P后面的AT的個數加上。
最后對1000000007取余輸出結果,屌屌的。

源代碼

//C/C++實現(暴力法超時)
#include <iostream>
#include <string>

using namespace std;

int main(){
    string s;
    cin >> s;
    long long count = 0;
    int indexP = s.find('P');
    while(indexP != -1){
        int indexA = s.find('A', indexP + 1);
        while(indexA != -1){
            int indexT = s.find('T', indexA + 1);
            while(indexT != -1){
                ++count;
                indexT = s.find('T', indexT + 1);
            }
            indexA = s.find('A', indexA + 1);
        }
        indexP = s.find('P', indexP + 1);
    }
    printf("%lld\n", count % (long long)1000000007);
    return 0;
}
//C/C++實現(AC代碼)
#include <iostream>
#include <string>

using namespace std;

int main(){
    string s;
    cin >> s;
    long long countT = 0, countAT = 0, countPAT = 0;
    for(int i = s.size() - 1; i >= 0; --i){
        if(s[i] == 'T'){
            ++countT;
        }
        else if(s[i] == 'A'){
            countAT += countT;
        }
        else if(s[i] == 'P'){
            countPAT += countAT;
        }
    }
    printf("%d\n", countPAT % (long long)1000000007);
    return 0;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容