Count and Say

本文介绍了一种名为“计数并说出”数列的生成方法,并提供了两种不同的Java实现方案来生成该数列的第n项。通过递进地读出每一项中数字的个数和类型来形成新的项。

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

题目来源:leetcode

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

1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.

Given an integer n, generate the n th sequence.

Note: The sequence of integers will be represented as a string.

/**
 * Created by a819 on 2017/8/10.
 */
public class CountandSay {
    public String countAndSay(int n) {
       String str[]=new String[n];//没必要都保存
        for (int y=0;y<n;y++)
            str[y]="";
        str[0]="1";
        String result="1";
        int i=0;
        while(i<n-1){
            int num=1;
            for (int j=1;j<str[i].length();j++){
                    if (str[i].charAt(j-1)==str[i].charAt(j))
                    {
                        num++;
                        //continue;
                    }
                    else {

                        str[i+1]+=(String.valueOf(num)+str[i].charAt(j-1));
                        num=1;
                    }

            }
            str[i+1]+=(String.valueOf(num)+str[i].charAt(str[i].length()-1));
            //result+=" ";
            //result+=str[i+1];
            result=str[i+1];//只求出第n的序列

            i++;

        }
        return result;


    }

    /**
     * 只记录前一个状态,不去记录每个状态
     * @param n
     * @return
     */
    public String countAndSay1(int n){
        if (n==1)
            return "1";
        int i=1;
        StringBuilder cur=new StringBuilder();//当前的序列
        cur.append("1");
        while (i<n){
            int num=1;
            StringBuilder next=new StringBuilder();//下个序列
            for (int j=0;j<cur.length();j++){
                if (j<cur.length()-1&&cur.charAt(j)==cur.charAt(j+1))
                    num++;
                else{
                    next.append(String.valueOf(num)).append(cur.charAt(j));
                    num=1;
                }


            }
            cur=next;
            i++;
        }
        return cur.toString();

    }

    public static void main(String[] args) {
    CountandSay c=new CountandSay();
        System.out.println(c.countAndSay1(4));
        //String s="jd"+" "+"sds"+String.valueOf(3);
        //System.out.println(s);
        }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值