PAT B1084 外观数列(C++)

PAT甲级目录 | PAT乙级目录

题目描述

B1084 外观数列

解题思路

字符串处理,对字符计数。

易错点

  • temp += to_string(cnt);
    • 预防出现计数值大于一位数的情况

也许陌生的知识点

  • to_string();
    • 实现将一个数转换为字符串,这个数可以是整型或浮点型
    • 需要的头文件:string
  • s.erase(ans.begin());
    • 删除字符串第一个字符
    • 所需头文件: string
  • s.empty()
    • 判断一个字符串是否为空字符串
    • 所需头文件: string

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
int n;
cin >> str >> n;
while(--n){
string temp;
while(!str.empty()){
temp += str[0];
int cnt = 0;
while(!str.empty() && str[0] == temp.back()){
str.erase(str.begin());
cnt++;
}
temp += to_string(cnt);
}
str = temp;
}
cout << str << endl;
return 0;
}