LeetCode-38. Count and Say
阿新 • • 發佈:2018-10-31
0.原題
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"
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"
1.程式碼
class Solution: def countAndSay(self, n): """ :type n: int :rtype: str """ if n == 1: return '1' else: counter = 1 pre_result = self.countAndSay(n-1) + '.' length = len(pre_result) result = '' for i in range(length-1): if pre_result[i] == pre_result[i+1]: counter += 1 else: result += str(counter) + pre_result[i] counter = 1 return result
2.思路
我們只要數出上一行相同數字即可,for迴圈遍歷這一行的每一個元素。
如果前後元素相同,則計數器加一;
如果前後元素不同,輸出計數器值+元素值,並“歸零”計數器。
這裡用pre_result表示上一行的結果,在末尾加上'.',是因為在上述方法中,只有前後元素不同的時候,才輸出。如果採用邊界判定,還需要複雜的判斷語句。
因此,直接在末尾加上一個'.',保證了最後一個元素的正確判定與輸出。