Description
The count-and-say sequence is the sequence of integers with the first five terms as following:
-
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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
Note: Each term of the sequence of integers will be represented as a string.
Example
Example 1:
Input: 1
Output: “1”
Explanation: This is the base case.
Example 2:
Input: 4
Output: “1211”
Explanation: For n = 3 the term was “21” in which we have two groups “2” and “1”, “2” can be read as “12” which means frequency = 1 and value = 2, the same way “1” is read as “11”, so the answer is the concatenation of “12” and “11” which is “1211”.
Submissions
首先这道题的含义类似于斐波拉契数,后面的数跟前面的数有关。每一个数是对上一个数进行报数,例如第一个数是1,第二个数对第一个数1报数,为1个1即11,第三个数对第二个数11进行报数,为两个1即21,第四个数对第三个数21进行报数,为一个2一个1即1211.因此这道题的解题思路是遍历每一个数字,记录当前重复数字的个数,将出现次数与该数字一同添加到结果中。
实现代码如下:
class Solution:
def countAndSay(self, n: int) -> str:
res='1'
for i in range(2,n+1):
pre=res
res=''
p=0#索引
flag=pre[0]#当前在计数的数字
count=0#记录当前出现的数字的次数
while p<len(pre):
if pre[p]==flag:
count+=1
p+=1
else:
res+=str(count)+pre[p-1]
flag=pre[p]#更换当前计数的数字
count=1#更新当前计数数字出现的次数
p+=1
res+=str(count)+pre[p-1]#最后一次计数的数字
return res
参考:https://blog.csdn.net/weixin_44740082/article/details/89339762