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.

 

class Solution {
public:
    string countAndSay(int n) {
        stringstream result;
        int count = 0, i = 0;
        string tmp;
        if(n == 1)
            return "1";
        else
        {
            tmp = countAndSay(n - 1);
            char now = tmp[0];
            while(tmp[i])
            {
                if(now == tmp[i])
                {
                    count++;
                    ++i;
                }
                else
                {
                    result << count << now;
                    count = 1;
                    now = tmp[i++];
                }
            }
            result << count << now;
            return result.str();
        }
    }
    
};
  • 注意最后result;防止tmp[i++] = ‘\n’时会跳过最后一个;
posted @ 2015-10-30 16:26  dylqt  阅读(116)  评论(0编辑  收藏  举报