Skip to content

38. Count and Say

难度:Easy

刷题内容

原题连接

  • https://leetcode.com/problems/count-and-say/

内容描述

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n where 1 �� n �� 30, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.


Example 1:

Input: 1
Output: "1"
Example 2:

Input: 4
Output: "1211"

˼· **- ʱ�临�Ӷ�: O(n)*- �ռ临�Ӷ�: O(1)***

����ҪŪ�����Ŀ����˼n == 1ʱ����1内容描述һ��1���� one 1��n == 2ʱ���ǡ�11内容描述��2��1���� two 1��n == 3ʱ���ǡ�21内容描述1��2��1��1���� one 2 one 1��n == 4ʱ���ǡ�1211内容描述�������ƣ�����д��ѭ��ģ������IJ������ɡ�

class Solution {
public:
    string countAndSay(int n) {
        string str;
        str.push_back('0' + 1);
        n--;
        while(n)
        {
            string temp;
            for(int i = 0;i < str.length();)
            {
                int j = 0;
                while(i + j < str.length() && str[i] == str[j + i])
                    ++j;
                temp.push_back('0' + j);
                temp.push_back(str[i]);
                i += j;
            }
            --n;
            str = temp;
        }
        return str;
    }
};

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组