@author: ZZQ
@software: PyCharm
@file: countAndSay.py
@time: 2018/11/9 14:07
说明:报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
1. 1
2. 11
3. 21
4. 1211
5. 111221
示例 1:
输入: 1
输出: "1"
示例 2:
输入: 4
输出: "1211"
思路: 从1开始,生成对应字符串,统计相邻的相同数字的个数并生成新的字符串,以此类推。
class Solution():
def __init__(self):
pass
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
value = ''
for i in range(1, n+1):
if i == 1:
value = '1'
else:
len_value = len(value)
count = 1
new_value = ''
if len_value == 1:
new_value += '1' + value
else:
for j in range(1, len_value):
if value[j-1] != value[j]:
new_value += str(count)
new_value += value[j-1]
count = 1
else:
count += 1
new_value += str(count) + value[len_value-1]
value = new_value
return value