[LeetCode] 38. Count and Say

本文介绍了一种基于递归和动态规划的方法来生成计数并描述序列。该序列从1开始,每一步都对前一步进行计数并描述。例如,1被描述为“一1”,即11;11被描述为“两1”,即21。文章提供了两种实现方案:一种是递归方法,另一种是使用动态规划方法。

Problem

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.

Note

用递归做这种找规律的题目。用stringbuilder。遍历递归而来的字符串s,当前字符与上一个相同时,只计数;不同时,添加计数和字符,然后重设计数和字符。

Solution

Recursion
public class Solution {
    public String countAndSay(int n) {
        if (n == 0) return "";
        if (n == 1) return "1";
        String s = countAndSay(n-1);
        char ch = s.charAt(0);
        int count = 1;
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == ch) count++;
            else {
                sb.append(count);
                sb.append(ch);
                count = 1;
                ch = s.charAt(i);
            }
        }
        sb.append(count);
        sb.append(ch);
        return sb.toString();
    }
}
DP
class Solution {
    public String countAndSay(int n) {
        if (n <= 0) return "";
        String[] dp = new String[n+1];
        dp[0] = "";
        dp[1] = "1";
        for (int i = 2; i <= n; i++) {
            StringBuilder sb = new StringBuilder();
            char ch = dp[i-1].charAt(0);
            int count = 1;
            for (int j = 1; j < dp[i-1].length(); j++) {
                if (ch == dp[i-1].charAt(j)) count++;
                else {
                    sb.append(count).append(ch);
                    count = 1;
                    ch = dp[i-1].charAt(j);
                }
            }
            sb.append(count).append(ch);
            dp[i] = sb.toString();
        }
        return dp[n];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值