- 题目:
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
-
题目大意:
输出字符串中PAT的个数 -
分析
对于字符串中的每个A,只用将其之前的P的个数和其之后的T的个数想乘,即可得到PAT的个数
代码实现:
#include <iostream>
#include <string>
using namespace std;
const int Max = 100005;
const int MOD = 1000000007;
int main()
{
string st;
int A[Max] = {0}, B[Max] = {0}, count1 = 0;
long long res;
cin >> st;
int len = st.size();
for(int i = 1; i < len; i++){ //求出每一位前面有多少个P
if(st[i-1] == 'P'){
count1 ++;
}
A[i] = count1;
}
count1 = 0;
for(int i = len-2; i >= 0; i--){ //求出每一位后面有多少个T
if(st[i+1] == 'T'){
count1 ++;
}
B[i] = count1;
}
for(int i = 0; i < len; i++){
if(st[i] == 'A'){
res += A[i] * B[i];
}
}
cout << res / MOD;
return 0;
}
更简洁的实现:
#include <iostream>
#include <string>
using namespace std;
const int MOD = 1000000007;
int main()
{
string st;
cin >> st;
int len = st.size(), res = 0, countt = 0, countp = 0;
for(int i = 0; i < len; i++){ //求出T的总数
if(st[i] == 'T')
countt++;
}
for(int i = 0; i < len; i++){
if(st[i] == 'P') countp++;
if(st[i] == 'T') countt--;
if(st[i] == 'A') res = (res + countp * countt) %MOD;
}
cout <<res;
return 0;
}