leetcode 038 Count and Say

本文介绍了一种名为“计数并描述”的有趣数列生成算法,通过递归方式统计相同数字出现次数,并以此生成新的序列。例如,从1开始生成后续序列:11, 21, 1211, 111221等。

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

题目

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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, generate the nth sequence.
Note: The sequence of integers will be represented as a string.

思路:

这题挻有意思的,关键要搞懂题目意思,它的意思是说让统计相同的数,然后用这个统计的个数和原来的一个数一起替换原来的那一串相同的数。举个例子:如果有连续5个1,则替换为51,4个2则替换为42。
比如:1211替换过程如下:有1个1,则1换成11;有一个2,则把2换成12;接下来有连续2个1,则把这两个1换成21;所以最终的结果是:1211 –> 111221
递归求解,然后统计重复字符。

代码:

public String countAndSay(int n)
{
    if(n==1) return String.valueOf(1);
    String s = countAndSay(n-1);
    char[] chars = s.toCharArray();
    StringBuilder res = new StringBuilder();
    int i=0;
    while(i<chars.length){
        int count = 1;
        char lastChar = chars[i];
        for(i = i+1; i < chars.length && chars[i] == lastChar; i++)
            count++;
        res.append(count).append(lastChar);
    }
    return res.toString();
}

结果细节(图):

image

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值