我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC
我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED
原题链接:
PAT-BASIC1040:https://pintia.cn/problem-sets/994805260223102976/problems/994805282389999616
PAT-ADVANCED1093:https://pintia.cn/problem-sets/994805342720868352/problems/994805373582557184
题目描述:
PAT-BASIC1040:
PAT-ADVANCED1093:
知识点:字符串
思路一:分别记录字符串“P”、“PA”、“PAT”的数量
这个思路的算法很巧妙。
依次遍历输入的字符串字符串。
(1)一旦发现P字符,则countP++。为了避免结果过大,让其对1000000007取余数。
(2)一旦发现A字符,那么该A字符肯定能和之前的“P”字符串组成“PA”字符串,因此令countPA += countP。为了避免结果过大,让其对1000000007取余数。
(3)一旦发现T字符,那么该T字符肯定能和之前的“PA”字符串组成“PAT”字符串,因此令countPAT += countPA。为了避免结果过大,让其对1000000007取余数。
时间复杂度是O(n),其中n为输入字符串的字符数。空间复杂度是O(1)。
C++代码:
#include<iostream>
#include<string>
using namespace std;
int main() {
string input;
cin >> input;
int countP = 0;
int countPA = 0;
int countPAT = 0;
for (int i = 0; i < input.length(); i++) {
if (input[i] == 'P') {
countP++;
countP %= 1000000007;
}else if (input[i] == 'A') {
countPA += countP;
countPA %= 1000000007;
}else {
countPAT += countPA;
countPAT %= 1000000007;
}
}
cout << countPAT;
return 0;
}
C++解题报告:
思路二:对每一个字符'A'计算其左边P的数量和右边T的数量
对一个确定位置的A来说,以它形成的PAT的个数等于它左边P的个数乘以它右边T的个数。我们用两个数组来分别计算每个位置左边P的数量和右边T的数量,一个数组countLeftP记录位置i左边的P个数,另一个数组countRightT记录位置i右边的T个数。
时间复杂度和空间复杂度均是O(n)。
C++代码:
#include<iostream>
#include<string>
using namespace std;
int main(){
string input;
cin >> input;
long countLeftP[input.length()]; //在索引i的左边有countLeftP[i]个P字符
countLeftP[0] = 0;
long total = 0;
for(int i = 1; i < input.length(); i++){
if(input[i - 1] == 'P'){
countLeftP[i] = countLeftP[i - 1] + 1;
}else{
countLeftP[i] = countLeftP[i - 1];
}
}
long countRightT[input.length()]; //在索引i的右边有countRightT[i]个T字符
countRightT[input.length() - 1] = 0;
for(int i = input.length() - 2; i >= 0; i--){
if(input[i + 1] == 'T'){
countRightT[i] = countRightT[i + 1] + 1;
}else{
countRightT[i] = countRightT[i + 1];
}
}
for(int i = 0; i < input.length(); i++){
if(input[i] == 'A'){
total += countLeftP[i] * countRightT[i];
}
}
printf("%ld", total % 1000000007);
return 0;
}
C++解题报告: