LeetCode 38. Count and Say

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, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

題意:這道題的題意真的是非常的復雜我真的是讀了很久還是沒讀懂。。。
這道題的含義是,數(shù)數(shù)字,1對應的就是字符串“1”,從2開始數(shù)前面的,所以它前面是“11”,3讀的是2,2里面有兩個1,所以是“21”,4,讀的是3,因為3是“21”,所以4是1個2,1個1,是“1211”。

Example 1:

Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"

java代碼:

public String countAndSay(int n) {
        if (n == 1) {
            return "1";
        } else {
            String output = countAndSay(n - 1), result = "";
            int index = 0;
            while (index < output.length()) {
                char current = output.charAt(index);
                int cursor = index, count = 0;
                while (cursor < output.length() && output.charAt(cursor) == current) {
                    cursor++;
                    count++;
                }
                char number = (char)(count + '0');
                result += number;
                result += current;
                index += count;
            }
            return result;
        }
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容