leetcode-38 Count And Say

本文介绍了一种特殊的整数序列——计数与描述序列,并提供了两种生成该序列的方法:递归解法与非递归解法。核心在于统计数字串中每个数字连续出现的次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

The count-and-say sequence is the sequence of integersbeginning as follows:
1, 11, 21,1211, 111221, ...

1 is read off as "one1" or 11.
11 is read off as "two1s" 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 integerswill be represented as a string.

 

问题分析:

    题目的意思指:每一个数字串,从最高位开始读起,对应每个数字的个数x个,其值为y;则记为xy;且每个数字串与其前一个数字串相关;

    这里是个很明显的递归,可以使用递归解法,也可以使用循环解法。两种解法核心都是统计数字串中每个数字连续出现的次数。

    这里仅需判断当前数字与后一个数字是否相同,

若相同,则count++,计算重复的数据次数。直至该数字与后一个数字不同,或者到了数组尾部;此时将该数字的次数与其值添加入结果String即可。


代码:

递归解法:

public class Solution {
    public String countAndSay(int n){
        String result = "";
        if (n <= 0)
            return result;
       
        return unitDo(n);
       
    }
   
    // 递归解法
    private String unitDo(int n) {
        if(n <= 1)
            return "1";
       
        String pre = unitDo(n - 1);
        char[] datas = pre.toCharArray();
        StringBuffer resultBuffer = new StringBuffer();
       
        int count = 1;
       
        for(int i = 0; i < datas.length; i++) {
            if( (i >= datas.length - 1) || datas[i]!= datas[i + 1] ) {
                resultBuffer.append(count);
                resultBuffer.append(datas[i]);
                count= 1;
            }else {
                count++;
            }
        }
        return resultBuffer.toString();       
    }
}
 

非递归解法:

    // 非递归解法
    public String countAndSay2(int n){
       
        String result = "";
        if (n <= 0)
            return result;
        String pre = "1";
        char[] datas;
        StringBuffer resultBuffer;
        int count;
       
        for (int j = 1; j < n;j++) {
            datas= pre.toCharArray();
            resultBuffer= new StringBuffer();
            count= 1;
           
            //核心部分不变
            for(int i = 0; i < datas.length;i++) {
                if( (i >= datas.length - 1) || datas[i]!= datas[i + 1] ) {
                    resultBuffer.append(count);
                    resultBuffer.append(datas[i]);
                    count= 1;
                }else {
                    count++;
                }
            }
            pre= resultBuffer.toString();
        }     
        return pre;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值