【Leetcode_总结】38. 报数 - python
Q:
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
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"
思路:这个题目看了好久才明白,(⊙_⊙)?。。思路就是先把题目中算好的几个数放到一个list里面,如果目标值在这个范围内,直接返回结果,如果不在,就算算吧,计算就是使用一个双指针,统计一下数量,然后加上对应的几个几就好了,效率有些低,代码如下:
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res = ['1','11','21','1211','111221']
if n <=5:
return res[n-1]
for i in range(4,31):
slow = 0
fast = 1
nums = ''
count = 1
print(res[i])
while fast < len(res[i]):
if res[i][slow] == res[i][fast]:
count+=1
fast+=1
else:
nums+=str(count)+str(res[i][slow])
slow = fast
fast+=1
count = 1
nums+=str(count)+str(res[i][slow])
res.append(nums)
print(res)
if i== n-2 :
return res[i+1]
放一个效率比较高的代码作为范本吧,其实思路是一样的,为啥差了这么多毫秒-_-|| 可能是往list里面存储消耗时间了
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res = '1'
for _ in range(n - 1):
cur = res[0]
count = 0
temp = ''
for i in res:
if i == cur:
count += 1
else:
temp += str(count) + cur
cur = i
count = 1
temp += str(count) + cur
res = temp
return res
将原先的res删除,换成一个temp = ''作为中间变量,代码如下:
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res = ['1','11','21','1211','111221']
if n <= 5:
return res[n-1]
nums = '111221'
for i in range(4, n):
temp = ""
slow = 0
fast = 1
count = 1
while fast < len(nums):
if nums[slow] == nums[fast]:
count+=1
fast+=1
else:
temp+=str(count)+str(nums[slow])
slow = fast
fast+=1
count = 1
temp+=str(count)+str(nums[slow])
nums = temp
return nums
效率稍有提升: