题目来源
https://leetcode.com/problems/count-and-say/
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"
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, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
题意分析
Input:n
Output:str
Conditions:依次数数,满足数数的条件即可
题目思路
注意到每次数的时候,不管是重复的1位,2位,或者更多位,都是用两位的list(a,b)来代替它,a为数量,b为那个数,此时j = j + 2就可以继续下一个循环
注意在我的代码的重复两位或多位的循环开始条件是不包括最后一位仅为一位的情况,所以单独判断
AC代码(Python)
_author_ = "YE"
# -*- coding:utf-8 -*- class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
L = ['']
if n == 1:
return ''
else:
for i in range(n - 1):
j = 0
while j < len(L):
x = L[j]
count = 1
if j + count == len(L):
L[j:j + 1] = ['', x]
else:
while j + count < len(L) and L[j + count] == x:
count = count + 1
L[j:j + count] = [str(count), x]
j = j + 2
return ''.join(L) s = Solution()
print(s.countAndSay(9))