[LeetCode] 38. Count and Say

题目链接:传送门

Description

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"

Solution

题意:

给定一个生成数的规则,求第n个数的值

思路:

关键是要理解规则,规则实际上就是把读法转化成数字,譬如 1123334,就是2个1,1个2,3个3,1个4,因此它的下一个数字即为 21123314

这里的做法用到了int到string的转化,我是用了stringstream来处理(),实际上用java的话这个处理会方便很多

class Solution {
public:
    string countAndSay(int n) {
        string res = "1";
        stringstream ss;
        while (--n) {
            string tmp = "";
            for (int i = 0, j = 1; i < res.length(); i = j) {
                while (j < res.length() && res[i] == res[j])  j++;
                string times = "";
                ss << j - i;
                ss >> times;
                ss.clear();
                ss.str("");
                tmp.append(times);
                tmp.append(1, res[i]);
            }
            res = tmp;
        }
        return res;
    }
};

补充:

啊,在 Discuss 里面看到了用std::to_string()来完成int到string的转化...0.0

把自己的 Solution 修改一下:

class Solution {
public:
    string countAndSay(int n) {
        string res = "1";
        while (--n) {
            string tmp = "";
            for (int i = 0, j = 1; i < res.length(); i = j) {
                while (j < res.length() && res[i] == res[j])  j++;
                tmp.append(to_string(j - i) + res[i]);
            }
            res = tmp;
        }
        return res;
    }
};
posted @ 2018-02-21 01:13  酒晓语令  阅读(104)  评论(0编辑  收藏  举报