原題
報(bào)數(shù)指的是,按照其中的整數(shù)的順序進(jìn)行報(bào)數(shù),然后得到下一個(gè)數(shù)。如下所示:
1, 11, 21, 1211, 111221, ...
1 讀作 "one 1" -> 11.
11 讀作 "two 1s" -> 21.
21 讀作 "one 2, then one 1" -> 1211.
給定一個(gè)整數(shù) n, 返回 第 n 個(gè)順序。
樣例
給定 n = 5, 返回 "111221".
解題思路
- 內(nèi)層for循環(huán)負(fù)責(zé)每次更新newS,比如把“1”更新為“11”
- 外層循環(huán)n次,表示n次更新,返回結(jié)果
完整代碼
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
i = 1
count = 1
newS = "1"
while i < n:
s = newS
newS = ""
for j in range(len(s)):
if j+1 < len(s) and s[j] == s[j+1]:
count += 1
else:
newS += str(count) + s[j]
count = 1
i += 1
return newS