• 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. 迭代问题,注意什么时候去更新变量
  • 相关阅读:
    supervisord + docker run = web页面管理运行的docker
    docker之Dockerfile实践用dockerfile构建nginx环境
    Dockerfile文件详解
    【docker】CMD ENTRYPOINT 区别 终极解读!
    golang html/template
    网络连接带宽的理论最大值
    Queue length 和 Queue depth 的区别
    .tar.gz 文件和 .tar.xz 文件的区别
    如何同时在Isilon的所有网卡上抓取网络包?
    Reimage Isilon cluster,结果忘记了修改管理口的netmask,怎么办?
  • 原文地址:https://www.cnblogs.com/Howfars/p/9872855.html
Copyright © 2020-2023  润新知