38. Count and Say
problem
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.
Subscribe to see which companies asked this question
后面一个元素用数字描述前一个元素,21描述成1211(1个2,1个1)
需要考虑的地方在于数字怎么分段,比如1112211(应该描述成312221),如何分段成111.22.11;遍历肯定可以,但是是不是太笨重了;
solution:wrong
首个元素是n的时候
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
strList = [str(n)]
for x in range(n - 1):
#print 'x',x
start = strList[x][0]
nums = 1
nStr = ''
for y in range(1,len(strList[x])):
#print 'y',y
if start == strList[x][y]:
nums += 1
else:
nStr += str(nums) + start
start = strList[x][y]
nums = 1
nStr += str(nums) +start
strList.append(nStr)
return strList[-1]
soultion:right
终于明白了,题目中的n不是对n进行推导,然后取第n个,而是对1进行推导取第n个。
将之前的初始值由str(n)变成‘1’就行了

浙公网安备 33010602011771号