LeetCode38 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, 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”
题源:here;完整实现:here
思路:
这道题的难点在于理解题目到底是什么意思。其实说白了就是一个读前面产生的数的游戏。比如:
111
有3个1,就读为31
1122
有2个1,2个2,就读为2122
明白这一点之后再看题目你就明白了,然后我们用迭代的方式解题,代码如下:

class Solution {
public:
    string recurse(string s){
        if (s.size() == 0) return "1";
        string result;
        int count = 1;
        while (s.size() > 0){
            if (s.size() >= 2 && s[0] == s[1]){
                s.erase(0, 1); count++;
            }
            else{
                result += count + '0'; result += s[0];
                s.erase(0, 1); count = 1;
            }
        }

        return result;
    }

    string countAndSay(int n) {
        string result;
        for (int i = 0; i < n; i++) result = recurse(result);

        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/80790307