Fork me on GitHub

【LeetCode】38. Count and Say

题目:

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.

Note: The sequence of integers will be represented as a string.

提示:

此题没有什么特别的技巧,根据题目要求的推导公式递推下去就行了。

注意:如果仔细思考其中的规律,不难发现不会有同一个数字连续出现4次及以上的情况(原因不妨自己仔细推敲一下)。因此在将字符出现次数的计数器(int型)追加到string当中去的时候,我们可以将它与'0'相加,以此转换为char型,这样子会比用to_string()方法来的速度更快。

代码:

class Solution {
public:
    string countAndSay(int n) {
        if (n == 1) return "1";
        string str = "11";
        string res;
        for (int i = 2; i < n; ++i) {
            char cur = str[0];
            int count = 1;
            res = "";
            for (int j = 1; j < str.size(); ++j) {
                if (str[j] == cur) {
                    ++count;
                } else {
                    res += (count+'0');
                    res += cur;
                    cur = str[j];
                    count = 1;
                }   
            }
            res += (count+'0');
            res += cur;
            str = res;
        }
        return str;
    }
};
posted @ 2015-08-27 21:29  __Neo  阅读(199)  评论(0编辑  收藏  举报