0.原题
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"
1.代码
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return '1'
else:
counter = 1
pre_result = self.countAndSay(n-1) + '.'
length = len(pre_result)
result = ''
for i in range(length-1):
if pre_result[i] == pre_result[i+1]:
counter += 1
else:
result += str(counter) + pre_result[i]
counter = 1
return result
2.思路
我们只要数出上一行相同数字即可,for循环遍历这一行的每一个元素。
如果前后元素相同,则计数器加一;
如果前后元素不同,输出计数器值+元素值,并“归零”计数器。
这里用pre_result表示上一行的结果,在末尾加上'.',是因为在上述方法中,只有前后元素不同的时候,才输出。如果采用边界判定,还需要复杂的判断语句。
因此,直接在末尾加上一个'.',保证了最后一个元素的正确判定与输出。