LeetCode38:Count and Say
阿新 • • 發佈:2018-11-14
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"
LeetCode: 連結
這題可神奇了。。我沒讀懂題。。。。正確理解題意:
首先給出前10個數字的序列:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211
題意就是
n=1時,輸出字串1;
n=2時,數上次字串中各個數值的個數,因為上個數字字串中有1個1,所以輸出11;
n=3時,由於上個字串是11,有2個1,所以輸出21;
n=4時,由於上個數字的字串是21,有1個2和1個1,所以輸出1211,依次類推......
解題思路:
宣告兩個字串,一個是存每次的結果,另一個作為暫存。
在輸入的迴圈次數下面,每次對前一個結構進行遍歷,
如果有相同的值就一直查這相同的值到底有多少個,然後將這個次數和這值本身新增到暫存字串尾部;
若無相同的值就將1和轉化成字串的該值新增到暫存字串的尾部。每次遍歷結束後,用暫存的字串更新結果字串,再將暫存字串清空。
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
'''ans是n應該輸出的字串 如果n=4 我們應該從1開始累積統計'''
ans = '1'
n -= 1
while n > 0:
'''res是之前暫存的字元'''
res = ''
'''是字首'''
pre = ans[0]
count = 1
for i in range(1, len(ans)):
if ans[i] == pre:
count += 1
else:
'''如果和之前的字首不相等 先記錄res 然後換新的字首比較'''
res += str(count) + pre
pre = ans[i]
count = 1
res += str(count) + pre
ans = res
n -= 1
return ans