145/300
- 报数
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 被读作 “one 1” (“一个一”) , 即 11。
11 被读作 “two 1s” (“两个一”), 即 21。
21 被读作 “one 2”, “one 1” (“一个二” , “一个一”) , 即 1211。
给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。
注意:整数顺序将表示为一个字符串。
示例 1:
输入: 1
输出: “1”
示例 2:
输入: 4
输出: “1211”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-and-say
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
先把题读懂了:
1. 1【我是一楼
2. 11 【一楼有一个1
3. 21 【二楼有俩个1
4. 1211【三楼有一个2,一个1
5. 111221【四楼有一个1,一个2,俩个1
…
思路1:用groupby分好了,然后用group的长度+uniquekey
python itertools.groupby() 使用方法
class Solution:
def countAndSay(self,n):
res = "1"
for _ in range(1, n):
tmp = ''
for k, g in itertools.groupby(res):
tmp += str(len(list(g))) + k
res = tmp
return res
思路2:
0 1 2 3 4 5
' 1 1 1 2 2 1 '
↑ ↑ ↑ ↑ ↑
class Solution:
def countAndSay(self, n: int) -> str:
def helper(s):
i, count, res = 0, 1, ''
while i < len(s) -1:
if s[i] == s[i+1]:
count += 1
else:
res += str(count)+s[i]
count = 1
i += 1
res += str(count) + s[i]
return res
res = '1'
for _ in range(1, n):
res = helper(res)
return res