题目:
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, …
1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
方法一:性能45ms
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
s = '1'
for i in range(2, n+1):
s = self.count(s)
return s
def count(self, s):
t = ''
count = 0
curr = '#'
for i in s:
if i != curr:
if curr != '#':
t += str(count) + curr
curr = i
count =1
else:
count +=1
t += str(count) + curr
return t
方法二:性能39ms
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
s = '1'
for _ in range(n-1):
let = s[0]
tmp = ''
count = 0
for l in s :
if let == l:
count += 1
else:
tmp += str(count) + let
let = l
count = 1
tmp += str(count) + let
s = tmp
return s
这里的_
:Python中对于无需关注其实际含义的变量可以用_
代替,这就和for i in range(5)
一样,因为这里我们对i
并不关心,所以用_
代替仅获取值而已。