zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):038-Count and Say


    题目来源


    https://leetcode.com/problems/count-and-say/

    The count-and-say sequence is the sequence of integers beginning as follows:
    1, 11, 21, 1211, 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 sequence.

    Note: The sequence of integers will be represented as a string.


    题意分析


    Input:n

    Output:str

    Conditions:依次数数,满足数数的条件即可


    题目思路


    注意到每次数的时候,不管是重复的1位,2位,或者更多位,都是用两位的list(a,b)来代替它,a为数量,b为那个数,此时j = j + 2就可以继续下一个循环

    注意在我的代码的重复两位或多位的循环开始条件是不包括最后一位仅为一位的情况,所以单独判断


    AC代码(Python)


     1 _author_ = "YE"
     2 # -*- coding:utf-8 -*-
     3 
     4 class Solution(object):
     5     def countAndSay(self, n):
     6         """
     7         :type n: int
     8         :rtype: str
     9         """
    10         L = ['1']
    11         if n == 1:
    12             return '1'
    13         else:
    14             for i in range(n - 1):
    15                 j = 0
    16                 while j < len(L):
    17                     x = L[j]
    18                     count = 1
    19                     if j + count == len(L):
    20                         L[j:j + 1] = ['1', x]
    21                     else:
    22                         while j + count <  len(L) and L[j + count] == x:
    23                             count = count + 1
    24                         L[j:j + count] = [str(count), x]
    25                     j = j + 2
    26         return ''.join(L)
    27 
    28 s = Solution()
    29 print(s.countAndSay(9))
  • 相关阅读:
    pytest知识梳理
    linux服务器时间不同步解决
    python re 多行匹配模式
    nginx--知识梳理
    tomcat--知识梳理
    利用springboot 重定向到静态资源功能,下载一些文件文件
    调试C++代码内存释放,在VS2019控制台显示内存泄露
    C++Primer第五版 第九章 习题9.22
    nginx 配置中间证书
    云苍穹消息推送代码
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5010968.html
Copyright © 2011-2022 走看看