问题
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"
or11
.11
is read off as"two 1s"
or21
.21
is read off as"one 2, then one 1"
or1211
.Given an integern
, generate then
th 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