PAT甲级1140 Look-and-say Sequence (20分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

Each input file contains one test case, which gives D (in [0, 9]) and a positive integer N (≤ 40), separated by a space.

​​Output Specification:

Print in a line the Nth number in a look-and-say sequence of D.

Sample Input:

1 8

Sample Output:

1123123111

二、解题思路

字符串处理的简单题,建立循环,每一次循环都遍历字符串,对每个字符,检查有多少个重复的,存放进tmp中,随后跳到下一个不重复的字符,代码还是比较易懂的。

三、AC代码

#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
using namespace std;
int main()
{
    
    
    string d;
    int n, k;
    cin >> d >> n;
    for(int i=1; i<n; i++)
    {
    
    
        string tmp = "";    //存放这一轮新的字符串
        int sze = d.size();
        for(int j=0; j<sze; j = k)
        {
    
    
            for(k=j; k<sze && d[k] == d[j]; k++);   //计算重复的字符数
            tmp += d[j] + to_string(k-j);   //加到当前新字符串
        }
        d = tmp;
    }
    cout << d << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/109062052
今日推荐