凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 38. Count and Say

分类:algorithm| 发布时间:2016-09-30 10:15:00


题目

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.

题意

求出第 n 个 count-and-say 序列。

解法

class Solution {
public:
    string countAndSay(int n) {
        string ret = "1";
        stringstream ss;
        char c;
        int count, size;
        while (--n > 0) {
            c = ret[0];
            count = 1;
            size = ret.size();
            ss.str("");
            for (int i = 1; i < size; ++i) {
                if (c != ret[i]) {
                    ss << count << c;
                    c = ret[i];
                    count = 1;
                } else {
                    ++count;
                }
            }

            ss << count << c;
            ret = ss.str();
        }

        return ret;
    }
};