leetcode 038 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.

题目大意是:
有一系列数:1, 11, 21, 1211, 111221, …
数的规律如下:
1 读作 “one 1”,转化为数字为11,为第二个数;
11 读作“two 1”,转化wie数字为21,为第三个数;
21 读作“one 2, one 1”,转化为数字为1211,为第四个数;
1211 读作“one 1, one 2, two 1”,转化为数字为111221,为第五个数;
111221 读作“three 1, two 1, one 1”,转化为数字为312111,为第六个数
…..
要求输如一个数n,输出序列的第n个数。

从以上的规律可知,我们只需求出在第i个数中某个数连续出现的次数即可,便可得到第i+1个数,规律比较简单。

代码如下:

int findSeqLen(string &str, int index) {
        int seq_len = 1;
        for(int i = index + 1; i < str.size(); ++i)
            if(str[i] == str[index]) ++seq_len;
            else break;
        return seq_len;

}

string countAndSay(int n) {
        string result = "1";
        if(n <= 0) return "";

        for(int i = 2; i <= n; ++i) {
            string new_str;
            for(int j = 0; j < result.size(); ) {
                int seq_len = findSeqLen(result, j);
                new_str += seq_len + '0';
                new_str += result[j];
                j += seq_len;
            }
            result = new_str;
        }
        return result;
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值