【leetcode】38. Count and Say
阿新 • • 發佈:2018-11-19
題目描述
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
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”讀作“1個1”,因而寫作“11”,這是第二行,而“1”是第一行; 而第二行的"11"讀作“2個1”,因而第三行寫作“21”; 第三行讀作“1個2,1個1”,寫作“1211”; …… 這樣應該就差不多了,第n行要用到第n-1行的結果,遍歷第n-1行的結果,根據上面的規則即可得到答案。 這樣就有下面兩個問題: 1.第n-1行結果怎麼來,我的解決方案是遞迴; 2.怎麼利用規則和n-1行的結果得到第n行結果,這裡首先要定義n=1時的結果,在編碼過程中,我發現按照我的程式碼n=2時求解也需要預先定義,於是也定義了n=2時的結果。然後從n-1結果的第二個字元開始遍歷就可以了。程式碼
public String countAndSay(int n) { if (n == 1) { return "1"; } if (n == 2) { return "11"; } String res = ""; String pre_res = countAndSay(n-1); int count = 1; char temp = pre_res.charAt(0); for (int i = 1;i < pre_res.length();i++) { if (pre_res.charAt(i) == temp) { count++; }else { res += String.valueOf(count) + temp; temp = pre_res.charAt(i); count = 1; } } res += String.valueOf(count) + temp; return res; }