leetcode38 - Count and Say - easy

Posted jasminemzy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode38 - Count and Say - easy相关的知识,希望对你有一定的参考价值。

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"

 

模拟题。循环。
三层循环。
循环1:做n次count and say。
循环2:即每次count and say,根据上一次的字符串,统计每个连续char的对象和次数,一个个append上去。
循环3:即用于统计某个具体char的次数。(while套while时重复母while的边界检查)。

 

实现:

class Solution {
    public String countAndSay(int n) {
        String crt = "1";
        for (int i = 0; i < n - 1; i++) {
            StringBuilder sb = new StringBuilder();
            
            int j = 0;
            while (j < crt.length()) {
                char c = crt.charAt(j);
                int cnt = 1;
                while (j + 1 < crt.length() && crt.charAt(j) == crt.charAt(j + 1)) {
                    cnt++;
                    j++;
                }
                sb.append(cnt);
                sb.append(c);
                j++;
            }
            
            crt = sb.toString();
        }
        return crt;
    }
}

 






















以上是关于leetcode38 - Count and Say - easy的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode题意分析&解答38. Count and Say

Leetcode38. Count and Say

LeetCode 38: Count and Say

[LeetCode 38] Count and Say

leetcode-38 Count And Say

LeetCode 38. Count and Say