PAT--1140 Look-and-say Sequence

题意:根据前一个串,构造下一个串,构造方法是统计连续字符的个数,比如112231,这个串的结构是,12(1有2个连在一起),22(2有2个连在一起),31(3有一个),11(1有一个)根据这个串构造的下一个串为12223111。
还有就是,输入的第二个数n应该是遍历的次数,但是本题由于输入d的时候就算构造了一次,故for循环中遍历n-1次,而不是n次。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string d;
    int n;
    while(cin >> d >> n)
    {
        for(int j = 1; j < n; j++)
        {
            string str;
            for(int i = 0; i < d.size(); i++)
            {
                str += d[i];
                int cnt = 1;
                while(i+1 < d.size() && d[i] == d[i+1])
                {
                    cnt++;
                    i++;
                }
                str += (char)(cnt+'0');
            }
            d = str;
        }
        cout << d << endl;
    }
    return 0;
}




猜你喜欢

转载自blog.csdn.net/mch2869253130/article/details/88050626