The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1 Output: "1"
Example 2:
Input: 4 Output: "1211"
LeetCode:链接
这题可神奇了。。我没读懂题。。。。正确理解题意:
首先给出前10个数字的序列:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211
题意就是
n=1时,输出字符串1;
n=2时,数上次字符串中各个数值的个数,因为上个数字字符串中有1个1,所以输出11;
n=3时,由于上个字符串是11,有2个1,所以输出21;
n=4时,由于上个数字的字符串是21,有1个2和1个1,所以输出1211,依次类推......
解题思路:
声明两个字符串,一个是存每次的结果,另一个作为暂存。
在输入的循环次数下面,每次对前一个结构进行遍历,
如果有相同的值就一直查这相同的值到底有多少个,然后将这个次数和这值本身添加到暂存字符串尾部;
若无相同的值就将1和转化成字符串的该值添加到暂存字符串的尾部。每次遍历结束后,用暂存的字符串更新结果字符串,再将暂存字符串清空。
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
'''ans是n应该输出的字符串 如果n=4 我们应该从1开始累积统计'''
ans = '1'
n -= 1
while n > 0:
'''res是之前暂存的字符'''
res = ''
'''是前缀'''
pre = ans[0]
count = 1
for i in range(1, len(ans)):
if ans[i] == pre:
count += 1
else:
'''如果和之前的前缀不相等 先记录res 然后换新的前缀比较'''
res += str(count) + pre
pre = ans[i]
count = 1
res += str(count) + pre
ans = res
n -= 1
return ans