我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC
我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED
原题链接:
PAT-BASIC1084:https://pintia.cn/problem-sets/994805260223102976/problems/994805260583813120
PAT-ADVANCED1140:https://pintia.cn/problem-sets/994805342720868352/problems/994805344490864640
题目描述:
PAT-BASIC1084:
PAT-ADVANCED1140:
知识点:字符串
思路:按题述规则编程即可
本题和LeetCode038——报数很像,不过其字符串放置的前后顺序刚好反了一下,思路也是差不多的。
这题其实有动态规划的影子,要知道外观数列的第N项,必须要知道其第N - 1项。
时间复杂度是O(n),其中n为第N项的字符串长度。空间复杂度是O(N)。
C++代码:
#include<iostream>
#include<string>
using namespace std;
string nextSequence(string s);
int main(){
int d, N;
cin >> d >> N;
string firstNum = "";
firstNum += d + '0';
string result = firstNum;
for(int i = 0; i < N - 1; i++){
result = nextSequence(result);
}
cout << result << endl;
return 0;
}
string nextSequence(string s){
string result = "";
int count;
for(int i = 0; i < s.length(); i++){
count = 1;
while(s[i + 1] == s[i]){
i++;
count++;
}
result += s[i];
result += count + '0';
}
return result;
}
C++解题报告: