首页 > 其他 > 详细

Count and Say

时间:2015-10-30 16:43:55      阅读:132      评论:0      收藏:0      [点我收藏+]

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’时会跳过最后一个;

Count and Say

原文:http://www.cnblogs.com/dylqt/p/4923620.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!