LeetCode-38 Count and Say

Description

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. 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值