LeetCode Notes_#38 Count and Say

LeetCode Notes_#38 Count and Say

Contents

题目

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"

思路和解答

题意

看了半天才看懂题目意思。
所谓count and say序列是这样的:后一个数是对前一个数的描述,如何描述呢?个数+数字(游程长度编码...)
比如:
第1个数:1,第二个数:11(1个1),第三个数:21(2个1),第四个数:1211(1个2,1个1)....以此类推
题目要求输入n,输出count and say的第n个数字

思路

统计上一个字符串里边重复出现某字符的次数,然后不断拼接,就可以写出后一个字符串;这算是迭代。

解答

#自己写的出了些小问题,参考了思路相似的解答
class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        s = '1'
        for _ in range(n-1):
            let, temp, count = s[0], '', 0#let是第一次出现的字符
            for l in s:#数一下后面有几个相同的字符
                if let == l:
                    count += 1#如果相同,就加1
                else:#如果不相同,就是下一个出现的字符
                    temp += str(count)+let#把前一个统计好的字符描述出来
                    let = l#更新let
                    count = 1#count重新从1开始(算上当前的l)
            temp += str(count)+let#把最后一个字母的描述加进去(因为循环到最后,最后一个字母不会被加入)
            s = temp#更新s
        return s

总结

  1. 避免越界问题:循环中不要用下标访问,而是直接访问每一个元素
  2. 循环中第一次和最后一次总是要重点考虑,有时候要做些细微的调整
  3. 迭代问题,注意什么时候去更新变量

转载于:https://www.cnblogs.com/Howfars/p/9872855.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值