420. Count and Say
文章目录
问题
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...1is read off as"one 1"or11.11is read off as"two 1s"or21.21is read off as"one 2, then one 1"or1211.
Given an integern, generate thenth sequence.Notice
The sequence of integers will be represented as a string.
解法
这题思路很简单,使用两个变量:count、item一个用来计数,一个用来存储当前统计的字符。初始值在循环外设定好为'1'即可。
代码
class Solution:
# @param {int} n the nth
# @return {string} the nth sequence
def countAndSay(self, n):
# Write your code here
result = '1'
for i in xrange(1, n):
numList = list(result)
item = numList[0]
count = 0
result = ''
for ch in numList:
if ch == item:
count += 1
else:
result = result + str(count) + item
item = ch
count = 1
result = result + str(count) + item
return result
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论