报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
1
11
21
1211
111221
1 被读作 "one 1" ("一个一") , 即 11。
11 被读作 "two 1s" ("两个一"), 即 21。
21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。
给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。
注意:整数顺序将表示为一个字符串。
python解法
class Solution:
def countAndSay(self, n):
# Write your code here
string = '1'
for _ in range(n-1):
count = 0
temp = string[-1]
result = ''
for i in range(len(string)-1, -1, -1):
if temp == string[i]:
count += 1
else:
result = str(count) + temp + result
temp = string[i]
count = 1
string = str(count) + temp + result
return string
错误的python解法
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
string = '1'
for i in range(n-1):
count = 0
temp = string[0]
res = ''
for j in range(len(string)-1):
if temp == string[j]:
count += 1
else :
res += str(count)+temp
temp = string[j]
count=0
string = res
return string
a = Solution()
print(a.countAndSay(5))
这种会报错temp=string[0] index out of range
有没有大佬可以教教我是为啥的哇
网友评论