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’时会跳过最后一个;
优质内容筛选与推荐>>
1、软工视频(21~25)-软件測试
2、使用Spring实现读写分离( MySQL实现主从复制)
3、仿百度手机助手标题栏透明度随ListView或ScrollView滚动改变的实现方法
4、Java中的结构语句
5、在IE6中对非<a>元素使用hover等伪类


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号