PAT甲级1140Look-and-say Sequence

时间:2020-08-05 00:19:49   收藏:0   阅读:78

题目链接

https://pintia.cn/problem-sets/994805342720868352/problems/994805344490864640

题解一

英语

思路、注意点和代码

// 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;
}

题解二

参考她的思路后,代码如下:

// 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/

欢迎讨论和交流!


原文:https://www.cnblogs.com/chouxianyu/p/13436352.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!