leetcode 38. Count and Say(报数) 解法 python

博客围绕LeetCode上的计数说序列问题展开。先给出问题描述,要求根据给定整数n(1 ≤ n ≤ 30)生成该序列的第n项。接着阐述解决思路,需遍历数字字符串,记录相同数字个数,处理好循环边界和最后字符。最后给出源码。

一.问题描述

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"

二.解决思路

比较简单的一道题,遍历当前的数字字符串,记录当前相同的数字个数,当当前字符与上个字符不同的时候,更新结果,在结果尾+相同个数和上个字符,注意for循环的边界和最后一个字符的处理

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我

欢迎大家一起套路一起刷题一起ac

三.源码

class Solution:
    def countAndSay(self, n: int) -> str:
        if n==1:
            return '1'
        if n==2:
            return '11'
        before='11'
        after=''
        for i in range(2,n):
            after=''
            samenum=1
            for t in range(1,len(before)):
                if before[t]==before[t-1]:
                    samenum+=1
                else:
                    after+=str(samenum)+before[t-1]
                    samenum=1
            after+=str(samenum)+before[len(before)-1]
            before=after
        return after
                
        

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值