晨太狼之狼堡

二货一枚快乐多

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.


Solution:

class Solution {
public:
    string countAndSay(int n) {
        if(n == 0) return "";
        string current = "1";
        string next = "";
        stringstream stream;
        while(--n)
        {
            int count = 1;
            current += '-';
            for(int i = 1; i < current.length(); ++i)
            {
                if(current[i] == current[i-1]) count++;
                else
                {
                    string tmp;
                    stream << count;
                    stream >> tmp;
                    next += tmp + current[i-1];
                    stream.clear();
                    count = 1;
                }
            }
            current = next;
            next.clear();
        }

        return current;
    }
};


阅读更多
文章标签: String
个人分类: LeetCode
上一篇Word Ladder II
下一篇Implement strStr()
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭