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>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
string str;
int num = 0;
int leftNumP[100000] = {0};
int main() {
cin>>str;
for(int i = 0;i < str.size();i++){
if(i > 0){
leftNumP[i] = leftNumP[i - 1];
}
if(str[i] == 'P'){
leftNumP[i]++;
}
}
int rightNumT = 0;
for(int i = str.size() - 1;i >= 0;i--){
if(str[i] == 'T'){
rightNumT++;
}else if(str[i] == 'A'){
num = (num + leftNumP[i] * rightNumT)%1000000007;
}
}
cout<<num;
return 0;
}
PAT计数:动态规划解决
本文介绍了一种使用动态规划算法来计算字符串中特定子串出现次数的方法。通过记录左侧P的数量和右侧T的数量,当遇到A时,计算出包含PAT的所有可能组合。此方法避免了重复计算,提高了效率。
501

被折叠的 条评论
为什么被折叠?



