[LeetCode] Count and Say

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,然后是两一个一(1 1),然后是两个一(2 1),然后是一个二一个一(1 2 1 1).求第n次的结果,存成字符串返回.
  • 解法: 嘛,其实感觉这题没意思,因为数字太大的话,时间会很长.数据小的话,就没意思了,因为数字的连续数量不会超过9个,总之,直接模拟就好了,用两个串来记当前串和下一串,读当前串结果存在下一串,然后读下一串,读的过程就是两个for循环,第一重是枚举第i个数,然后跳到下一个与i不同的数,第二重就是一直循环把相同的数跑完就好了,然后用j-i得出连续的数有多少个.复杂度:O(n*m)m在递增,一次比一次长.数据大概应该是只有1到18吧.18组测试数据.
class Solution {
public:
    string countAndSay(int n) {
        string akResult[2];
        int iCurIdx = 0;
        for (akResult[iCurIdx].push_back('1'); --n; iCurIdx ^= 1) {
            akResult[iCurIdx ^ 1].clear();
            for (int i = 0, j = 0; i < (int)akResult[iCurIdx].size(); i = j) {
                for (j = i; j < (int)akResult[iCurIdx].size() && akResult[iCurIdx][j] == akResult[iCurIdx][i]; ++j);
                akResult[iCurIdx ^ 1].push_back((j - i) + '0');
                akResult[iCurIdx ^ 1].push_back(akResult[iCurIdx][i]);
            }
        }
        return akResult[iCurIdx];
    }
};

欢迎访问我的github,我的leetcode持续更新: https://github.com/tsfissure/LeetCode

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值