Easy
Count-and-say 序列是一個如下的整數(shù)序列沮尿。 給定一個整數(shù)n,返回第n個序列。序列用string表示姿搜。
1, 11, 21, 1211, 111221, ...
1讀作一個1,或11
11讀作兩個1捆憎,或21
21讀作一個2一個1舅柜,或1211
Leecode把此題歸為easy檔,我倒是覺得有些難度躲惰。
最開始我把題理解錯誤致份,認(rèn)為是: 第一個數(shù)是n,那么由n衍生出的coutn-and-say序列的第n個值是什么礁扮?所以就有了下面的code知举。(開始是string=str(n)
)。
將問題簡化為求上面序列的第n個值太伊,應(yīng)該有更簡單的辦法雇锡,歡迎反饋。
from itertools import groupby
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 0 or n == 1:
return str(n)
string = '1'
for _ in xrange(n-1):
keys = [key for key, _ in groupby(string)]
counts = [len(list(group)) for _, group in groupby(string)]
resp = ''
for key, count in zip(keys,counts):
resp += str(count)+key
string = resp
return string