leetcode-38 Count And Say

问题描写叙述:

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;
    }


转载于:https://www.cnblogs.com/clnchanpin/p/7398018.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值