字元串
APPAPT
中包含了兩個單詞
PAT
,其中第一個
PAT
是第 2 位(
P
),第 4 位(
A
),第 6 位(
T
);第二個
PAT
是第 3 位(
P
),第 4 位(
A
),第 6 位(
T
)。
現給定字元串,問一共可以形成多少個
PAT
?
輸入格式:
輸入隻有一行,包含一個字元串,長度不超過105,隻包含
P
、
A
、
T
三種字母。
輸出格式:
在一行中輸出給定字元串中包含多少個
PAT
。由于結果可能比較大,隻輸出對 1000000007 取餘數的結果。
輸入樣例:
APPAPT
輸出樣例:
2
題解
先用數組記錄截止到數組s中的某個字母時P的數量
再由s從後往前記錄T的個數
若讀到A,則将此A前的P個數與A後的T個數相乘
所有A加和後再mod即為ans
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MOD = 1000000007;
char s[100200];
int main()
{
int np[100200] = { 0 }, nt = 0, ans = 0, len;
scanf("%s", s);
len = strlen(s);
for (int i = 0; i < len; i++) {
if (i > 0)
np[i] = np[i - 1];
if (s[i] == 'P')
np[i]++;
}
for (int i = len - 1; i >= 0; i--) {
if (s[i] == 'T')
nt++;
else if (s[i] == 'A')
ans = (ans + np[i] * nt) % MOD;
}
printf("%d", ans);
return 0;
}