LeetCode算法题解 38-报数

题目描述

题解:

这道题目的其实是很简单的(难度的分类也是简单),但是乍一看并不是那么好做,首先看懂题目意思
比如1211,怎么报数呢?从左到右开始报数:1个1、1个2、2个1 => 111221
第一种解法
n最大为30,那我就一个个地数出来,不过这方法太耗时间了,而且容易出错。
第二种解法

  1. 写一个getCountResultBySqe(string str),传入一个字符串,比如1211,得到报数的结果为111221
  2. 写一个递归(循环也可以),当n==1时,直接返回1,否则返回getCountResultBySqe(countAndSay(n - 1)),其实也就是自顶向下求出对应的报数结果。

代码(递归):

class Solution {
public:
    string countAndSay(int n) {
        // 比如:1211,就是1个1、1个2、2个1 => 111221
        // 1:1
        // 2:11
        // 3:21
        // 4:1211
        // 5:111221
        // 6:312211
        // 7:13112211
        // 8:1113212221
        if(n == 1)
        {
            return "1";
        }
        return getCountResultBySqe(countAndSay(n - 1));
    }  
    
    string getCountResultBySqe(string str)
    {
        // 给定一个序列得到报数的结果
        string res = "";
        int i = 1;
        int cnt = 1;
        char pre = str[0];
        while(i < (int)str.size())
        {
            if(str[i] == pre)
            {
                cnt++;
            }
            else
            {
                char cnt_ch = '0' + cnt;
                res += cnt_ch;
                res += pre;
    
                cnt = 1;
                pre = str[i];
            }
            i++;
        }
        char cnt_ch = '0' + cnt;
        res += cnt_ch;
        res += pre;
        return res;
    }

};

代码(循环)

class Solution {
public:
    string countAndSay(int n) {
        string str = "1";
        for(int i = 1; i <= n-1; i++)
        {
            str = getCountResultBySqe(str);
        }
        return str;
        
    }  
    
    string getCountResultBySqe(string str)
    {
        // 给定一个序列得到报数的结果
        string res = "";
        int i = 1;
        int cnt = 1;
        char pre = str[0];
        while(i < (int)str.size())
        {
            if(str[i] == pre)
            {
                cnt++;
            }
            else
            {
                char cnt_ch = '0' + cnt;
                res += cnt_ch;
                res += pre;
    
                cnt = 1;
                pre = str[i];
            }
            i++;
        }
        char cnt_ch = '0' + cnt;
        res += cnt_ch;
        res += pre;
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值