PAT(Advanced Level) 1140 Look-and-say Sequence (20 分)

题目描述

Look-and-say sequence is a sequence of integers as the following:

D, D1, D111, D113, D11231, D112213111, …

where D is in [0, 9] except 1. The (n+1)st number is a kind of description of the nth number. For example, the 2nd number means that there is one D in the 1st number, and hence it is D1; the 2nd number consists of one D (corresponding to D1) and one 1 (corresponding to 11), therefore the 3rd number is D111; or since the 4th number is D113, it consists of one D, two 1’s, and one 3, so the next number must be D11231. This definition works for D = 1 as well. Now you are supposed to calculate the Nth number in a look-and-say sequence of a given digit D.

输入说明

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

输出说明

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

分析:通过描述前一个字符串的信息得到下一个字符串,从str[i]开始,往后逐一判断相邻字符是否相等,若是则cnt++;否则同时输出temp和cnt。然后进入下一个循环。`

#include
using namespace std;

int main()
{
     
    int d, n;
    cin >> d >> n;
    string str = to_string(d);//这里一个优化的写法无需定义d,直接cin >> str >> n
    //注意这里只需进行n - 1次描述
    while(n-- > 1)
    {
     
        int len = str.length();
        string next = "";
        for(int i = 0; i < len; i++)
        {
     
            int cnt = 1;//计数初始值至少一个
            char temp = str[i];
            while (i + 1 <= len - 1 && str[i] == str[i+1]) 
            {
     
                i++;
                cnt++;
            }
            next += temp + to_string(cnt);//记录当前重复的字符和个数
        }
        str = next;
    }
    cout << str << endl;
    return 0;
}

一个坑点:
a = a + b 和 a += b这两个语句的速度不一样的,刚开始我使用前者导致有一个测试点运行超时。因此,在编写程序的时候,应尽可能用 += 写法

一个细节
for 循环中的 i++命令是在执行完一次循环之后再执行,在边界处理的时候需要注意。

你可能感兴趣的:(PAT甲级,字符串)