从零开始的LC刷题(12): Count and Say

原题:

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

 

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

看了题很懵逼,遂百度了一下,发现意思就是2是在1的基础上得来的,3是来自于2的读法的以此类推,那个博客正好写了代码我就按他的思想(没有算法)写了代码出来,发现性能弱鸡内存占用又高,我就把递归改成循环调用结果性能还是很辣鸡,结果如下:

Success

Runtime: 32 ms, faster than 15.33% of C++ online submissions for Count and Say.

Memory Usage: 59 MB, less than 15.92% of C++ online submissions for Count and Say.

代码:

class Solution {
public:
    string countAndSay(int n) {
        string str="";
        string r="1";
        for(int s=0;s<n-1;s++){
            str=r;
            r="";
            for(int i=0;i<str.size();i++)
            {
                int m=1;
                while(str[i+1]==str[i]){i++;m++;}
                r=r+to_string(m)+str[i];
            }
        }
        return r;
    }
    
};

之后发现我蠢了,r=r+to_string(m)+str[i];应该写成r+=to_string(m)+str[i];,结果就变成:

Success

Runtime: 4 ms, faster than 100.00% of C++ online submissions for Count and Say.

Memory Usage: 8.9 MB, less than 61.26% of C++ online submissions for Count and Say.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值