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.
题意:
count-and-say序列是如上所示的序列,比如,1,可以读作1个1, 所以下一个数就是11,11可以读作2个1,所以,下一个就是21。给定一个整数n,生成序列的第n个整数序列,该整数序列表示为字符串。
分析:
给定一个整数n,从1开始。不断的获取下一个序列。
采用–n的循环。循环n-1次。
s=getNext(s).
函数:getNext,不断的获取下一个序列。
通过循环迭代器,返回不同于*i的值的下标,就能统计出这个数的个数,然后和i一齐写入到字符流。移动下标,循环i

// LeetCode, Count and Say
// @author 连城 (http://weibo.com/lianchengzju)
//1, 11, 21, 1211, 111221
// 时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
    string countAndSay(int n) {
        string s("1");

        while (--n)
            s = getNext(s);//获得下一个序列。

        return s;
    }

    string getNext(const string &s) {
        stringstream ss;//定义一个字符流。

        for (auto i = s.begin(); i != s.end(); ) 
        {
            auto j = find_if(i, s.end(), bind1st(not_equal_to<char>(), *i)); //返回一个迭代器。当s=1时,返回end迭代器。
            //在i到end范围内找到  操作 i   bind1st(const Operation& op, const T& x)就是这么一个操作:x op value,而bind2nd(const Operation& op, const T& x)  这里就是找到不等于i的字符。
            ss << distance(i, j) << *i;//将i的值和i,j的距离写入到里面去。
            i = j;//i更新成j的距离。
        }

        return ss.str();//将流转换成字符串。
    }
};

新知识点:
stringstream 定义字符流。
.str()将字符流转换成字符串。
bind1st(const Operation& op, const T& x)就是这么一个操作:x op value
bind2st就是 value op x
find_if(i, s.end(), bind1st(not_equal_to(), *i)); 在i和s.end()范围内找到op
distance(i, j) 求i,j的距离。
ss << distance(i, j) << *i; 将数字写入流。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值