天天看點

算法題-Count and Say

題目來自 LeetCode

The count-and-say sequence is the sequence of integers with the first five terms as following:

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 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”

第二個字元串是 “11”(數前一個字元串中的數字個數,前一個有:一個“1”)

第三個字元串是 “21”(前一個字元串有:兩個“1”)

第四個字元串是 “1211”(前一個字元串有:一個“2”和一個“1”)

按照這個規律,輸入 n,輸出對應的第 n 個字元串

這道題是一道簡單的遞歸題,我是用 Java 寫的,如果你也使用 Java 那麼我建議你使用 StringBuilder 做字元串的拼接,這樣可以很好的提高性能

以下是答案源碼: