38. Count and Say

本文介绍了一种名为“计数并说”的数列生成算法,通过解析序列中数字的出现次数和类型来生成新的序列。文章提供了两种实现方式:使用String和StringBuilder,详细解释了每一步的逻辑和代码实现。

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

38. 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”

题意理解

这道题根据给的5个例子可以知道它是在计数,从第一个序列1开始,后面的每一个序列就是在对前面一个数列进行计数,1是1个1所以是11(n=2时),11是2个1所以是21(n=3),21是1个2和1个1所以是1211…以此类推,遇到不同的数出现就要重新计数,数量在前具体数字在后

纯String解法

需要用到string的charAt(int index)方法,可以返回指定索引处的 char 值,
用到两个String pre和res来传递上一个string和正在计算的string

class Solution {
    public String countAndSay(int n) {
        if(n==0) return null;
        
        String res="1";
        for(int i=1;i<n;i++){
            String pre=res;
            res="";
            int cnt=1;
            char num=pre.charAt(0);
            for(int j=1;j<pre.length();j++)
            {
                if(pre.charAt(j)==num){
                    cnt++;
                }
                else{
                    res=res+cnt+num;
                    num=pre.charAt(j);
                    cnt=1;
                }
            }
            res=res+cnt+num;
        }
        return res;
    }
}

改写为stringbuilder

class Solution {
    public String countAndSay(int n) {
        if(n==0) return null;
        
        StringBuilder res=new StringBuilder("1");
        for(int i=1;i<n;i++){
            StringBuilder pre=res;
            res=new StringBuilder();
            int cnt=1;
            char num=pre.charAt(0);
            for(int j=1;j<pre.length();j++)
            {
                if(pre.charAt(j)==num){
                    cnt++;
                }
                else{
                    res=res.append(cnt).append(num);
                    num=pre.charAt(j);
                    cnt=1;
                }
            }
            res.append(cnt).append(num);
        }
        return res.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值