[LeetCode] Count and Say

470 查看

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

开始没懂题目的原意,以为n是任意数,然而是从1开始count and say的第n个数。
是以,要用递归做这种找规律的题目。用stringbuilder,既可添加char,又可以添加int。遍历递归而来的字符串s,当前字符与上一个相同时,只计数;不同时,添加计数和字符,然后重设计数和字符。

Solution

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();
    }
}