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"
複製代碼
count-and-say序列是前五項爲整數的序列:
1 1
2 11
3 21
4 1211
5 111221
1被讀做「一個 1」或「11」。 11被讀做「兩個1」或21。 21被讀做「1個2,而後1個1」或1211。
給定一個整數n,其中1≤n≤30,生成count-and-say序列的第n項。
注意:整數序列的每一項都表示爲字符串。
示例1:
輸入:1
輸出:「1」
示例2:
輸入:4
輸出:「1211」bash
本題其實很簡單,可是題目理解上可能不同,本人一開始沒有理解題意,看了下別人的解釋才最終明白。本題主要是一個統計和說兩個概念,按照咱們正常習慣從左往右數和說,好比「1」,咱們統計1的個數爲1,因此count-and-say格式,第二層就是「11」,也就是一個1的意思,對應「11」而言,咱們統計的1的個數爲2,按照count-and-say格式,就是「21」,也就是第三層答案,2個1的意思。同理「21」,就是1個2,1個1,因此就是「1211」。本題的解題思路也是如此。app
按照咱們的思路來編輯,代碼以下ui
String first = "1";
if (n <= 1) {
return first;
}
StringBuilder stringBuilder = new StringBuilder(first);
for (int i = 1; i < n; i++) {
StringBuilder stringBuilder1 = new StringBuilder();
char pre = stringBuilder.charAt(0);
int count = 1;
for (int m = 1; m < stringBuilder.length(); m++) {
if (stringBuilder.charAt(m) != pre) {
stringBuilder1.append(count).append(pre);
pre = stringBuilder.charAt(m);
count = 1;
continue;
}
count++;
}
stringBuilder1.append(count).append(pre);
stringBuilder = stringBuilder1;
}
return stringBuilder.toString();
複製代碼
時間複雜度: 該方案用了循環,循環層數爲2,即T(n)=O(n^2)spa
空間複雜度: 該方案沒有使用額外的空間,因此空間複雜度是O(1);翻譯
本題的大體解法如上所訴,瞭解題意仍是很重要的。code