题目来源
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)
1 _author_ = "YE" 2 # -*- coding:utf-8 -*- 3 4 class Solution(object): 5 def countAndSay(self, n): 6 """ 7 :type n: int 8 :rtype: str 9 """ 10 L = ['1'] 11 if n == 1: 12 return '1' 13 else: 14 for i in range(n - 1): 15 j = 0 16 while j < len(L): 17 x = L[j] 18 count = 1 19 if j + count == len(L): 20 L[j:j + 1] = ['1', x] 21 else: 22 while j + count < len(L) and L[j + count] == x: 23 count = count + 1 24 L[j:j + count] = [str(count), x] 25 j = j + 2 26 return ''.join(L) 27 28 s = Solution() 29 print(s.countAndSay(9))