【LeetCode 38】Count and Say(Python)


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, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

题目分析:

分析给定数组的规律,根据输入的行数,输出所在行的具体内容。

给定数据的规律为:第一行--1;之后每一行的内容为上一行的数字串从左到右读出来。

第二行---一个‘1’ -----11

第三行---两个‘1’----21

第四行---一个‘2’一个‘1’----1211

。。。 。。。

示例:

Input:4                        Output:1211

方法一:

  1. 思路:由于每一行的内容为前一行的内容从左到右顺序读出,而且需要统计每个数字出现的次数。(此处有一点需要注意:相邻两个数字一样,累加统计。)所以要都读出的内容必须是字符型(char),不能是数字类型(int,float等)否则无法进行统计数字出现次数。   通过循环来进行统计读出。
  2. 我觉得此题的解体关键主要就是想清楚要将数组内容转换成字符型。
  3. 代码:
    class Solution:
        def countAndSay(self, n):
            """
            :type n: int
            :rtype: str
            """
            b='1'   #将第一行的1换成字符类型,便于下一行的读出
            for i in range (n-1):    #(n-1)是因为第一行不需要处理,直接可以读出
                a,c,count=b[0],'',0   #a用来读取上一行的第一个字符,c用来存放读出的内容(char),count用来统计
                for j in b:   
                    if a==j:
                        count+=1
                    else:
                        c+=str(count)+a   #注意一定要将count转换为字符型,否则两个数就会相加(变成数学公式)。
                        a=j
                        count=1
                c+=str(count)+a
                b=c
            return b


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值