38. Count and Say (E)

本文介绍了一种生成计数与描述序列的方法,通过创建next方法根据上一个序列计算下一个序列,利用List保存已计算序列避免重复计算。适用于1至30的整数输入,返回对应的计数与描述序列。

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

Count and Say (E)

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.


题意

定义一组数字序列为:每一个数字序列都是对上一个数字序列的“描述”,如第一个序列为“1”,第二个序列为“11”(描述第一个序列中有1个1),第三个序列为“21”(描述第二个序列中有2个1),第四个序列为“1211”(描述第三个序列中有1个2、1个1)……要求返回第n个序列。

思路

创建一个next(String s)方法来根据上一个序列计算下一个序列。为了避免多次重复的计算,用一个List来保存各个序列。


代码实现

class Solution {
    // 保存计算过的序列,避免重复运算
    private List<String> list = new ArrayList<>();

    public String countAndSay(int n) {
        // 首先找是否已经计算过对应的值
        if (n <= list.size()) {
            return list.get(n - 1);
        }
		
        // 尚未计算对应值,则从已有的最后一个序列开始计算到指定序列
        while (list.size() < n) {
            String s = list.size() == 0 ? null : list.get(list.size() - 1);  // 注意没有一个已计算的情况
            list.add(next(s));
        }

        return list.get(n - 1);
    }

    private String next(String s) {
        // 特殊情况,计算第一个序列
        if (s == null) {
            return "1";
        }
        
        StringBuilder sb = new StringBuilder();
        int count = 1;
        for (int i = 0; i < s.length(); i++) {
            if (i > 0) {
                if (s.charAt(i) == s.charAt(i - 1)) {
                    count++;
                } else {
                    sb.append(count);
                    sb.append(s.charAt(i - 1));
                    count = 1;
                }
            }
        }
        sb.append(count);
        sb.append(s.charAt(s.length() - 1));
        return sb.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值