The count-and-say sequence is the sequence of integers beginning as follows: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 sequence.
Note: The sequence of integers will be represented as a string.
題意分析:
本題是將數字從1開始,將當前數字轉化為口語對應的數字。比如1口語是1個1,記作11;11讀作2個1,記作21;21讀作1個2,1個1,記作1211……
'1'是第一個數字,根據輸入的數字n,計算第n個這樣的數字。
說起來比較拗口,對照着例子可以感受一下……
解答:
如果你理解題意,那么解答就很簡單。直接循環,每個數字按照題目要求翻譯成口語對應的數字,按照順序找到第n個返回就行了。
Leetcode給的評級是Easy,這是對於程序難度來說,然而對於題意來說容易理解偏。
AC代碼:
class Solution(object): def countAndSay(self, n): if n < 2: return '1' ret_str = '1' while n > 1: temp, current_num = '', 0 for i, v in enumerate(ret_str): if i > 0 and v != ret_str[i - 1]: temp += str(current_num) + ret_str[i - 1] current_num = 1 else: current_num += 1 ret_str = temp + (str(current_num) + ret_str[-1] if current_num != 0 else '') n -= 1 return ret_str
后話:
其實這道題有個很有意思的地方,即輸出的數字中永遠不可能有大於3的數字,只會出現1、2、3三個數字,你能夠證明嗎?