LeetCode 第 38 题:外观数列

2024-03-17  本文已影响0人  放开那个BUG

1、前言

题目描述

2、思路

就是按照题目的步骤,从最小的单元开始,一步步增大

3、代码

class Solution {
    public String countAndSay(int n) {
        if (n == 1) {
            return "1";
        }
        String num = countAndSay(n - 1);
        StringBuilder sb = new StringBuilder();
        int count = 0;
        for (int i = 0; i < num.length(); i++) {
            if(i + 1 < num.length() && num.charAt(i) == num.charAt(i + 1)){
                count++;
                continue;
            }
            sb.append(count + 1).append(num.charAt(i));
            count = 0;
        }

        return sb.toString();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读