https://pintia.cn/problem-sets/994805342720868352/problems/994805344490864640
corresponding to
与…相一致,我之前似乎记成了“根据……”
// Problem: PAT Advanced 1140
// URL: https://pintia.cn/problem-sets/994805342720868352/problems/994805344490864640
// Tags: String
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string generateNext(string str){
// 字符串长度
int len = str.length();
// 生成下一个字符串
stringstream next;
for (int i = 0; i < len; i++){
// 获取key
char key = str[i];
// 统计key出现的次数
int count = 1; // key出现的次数
int j = i + 1; // 作为下标用来循环
while (j < len)
{
if (key == str[j])
count += 1;
else{
// 发现了和key不一样的字符str[j],即该key的数量统计结束,且外层循环应接着从j开始
// i=j-1而非i=j,是因为外层循环结束后i还要++
i = j - 1;
break;
}
j++;
}
// 将该key及其次数保存至新字符串
next << key;
next << count;
// 处理样例中第3个字符串D111的情况,即内层循环不是通过break结束而是一直循环至j==len的情况
// 这种情况则不用再进行外层循环了,因为最后一个key一直延续到了串的结尾
if (j == len)
break;
}
return next.str();
}
int main()
{
// D是0到9
// 第n+1个数字是第n个数字的一种描述
string s;
int n;
cin >> s >> n;
n -= 1; // 用户输入的其实就是第1个串
while (n--){
// cout << s << endl;
s = generateNext(s);
}
cout << s << endl;
return 0;
}
j-i
实现计数功能,而非像我一样定义变量count进行计数s[i]==s[j]
放在内层循环的判断条件中,而非像我一样使用if+break
语句i++
,而是直接i=j
(前提是j
此时是下一个待统计字符的下标)j
从i
开始,而非像我一样从i+1
开始。这一点是我的想法比较好参考她的思路后,代码如下:
// Problem: PAT Advanced 1140
// URL: https://pintia.cn/problem-sets/994805342720868352/problems/994805344490864640
// Tags: String
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string s; // 用户输入的数字,最终结果
int n, j; // 第n个字符串,循环遍历
cin >> s >> n;
n -= 1; // 用户输入的其实就是第1个串
while (n--){
string t = "";
for (int i = 0; i < s.length(); i=j){
for (j = i+1; j < s.length() && s[i] == s[j]; j++);
t += s[i];
t += to_string(j - i);
}
s = t;
}
cout << s << endl;
return 0;
}
作者:@臭咸鱼
转载请注明出处:https://www.cnblogs.com/chouxianyu/
欢迎讨论和交流!
PAT甲级1140Look-and-say Sequence
原文:https://www.cnblogs.com/chouxianyu/p/13436352.html