zoukankan      html  css  js  c++  java
  • 38. Count and Say

    <题意理解困难><字符串遍历出界>

    题目

    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"
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/count-and-say
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    View Code

    解析:第n个数经过报数后得到n+1

    当n=1:'1',读作【一个一】,即11

    当n=2:'11',读做【两个1】,即21

    当n=3:'21',读作【一个二】和【一个一】,即1211

    ...

    以此类推

    我的思路

     1.先把已知的1-5用字典表示,遇到直接返回结果

    2.接下来就是迭代到第n个序列

    3.每一次迭代,统计前一项中相同的字符,即为几个几,如碰到111 -> 三个一 -> 31

    4.最后返回迭代的结果 -> aftScn

    我的实现

    class Solution(object):
        def countAndSay(self, n):
            """
            :type n: int
            :rtype: str
            """
            init = {
                1:'1',
                2:'11',
                3:'21',
                4:'1211',
                5:'111221'
            }
            if n in init:
                return init[n]
            preScn = '111221'
            aftScn = ''
            #迭代到第n个序列
            for i in range(6,n+1):
                #判断str[i]==str[i+1]的时候会出界
                #因此干脆在字符串后面多加一位
                preScn=preScn+"@"  
                count=1
                aftScn = ''
                #扫描前一项序列的字符串
                for w in range(len(preScn)-1):
                    if preScn[w] == preScn[w+1]:
                        count+=1
                    else:
                        aftScn+=str(count)+preScn[w]
                        count=1
                #把处理完的字符串的结果作为前一项参与继续迭代        
                preScn = aftScn
            return aftScn

    题解

    总结

    1.扫描字符串判断str[i]==str[i+1]如何处理尾边界的情况

    我的思路:

    1.字符串后面加入一个无关字符

    2.字符循环时,字符串长度-1(因为加入了一个无关字符)

  • 相关阅读:
    常用的CSS命名规则 (web标准化设计)
    有哪些概率论和数理统计的深入教材可以推荐?
    CV2X国内现状分析
    隐私计算,新能源汽车“安全上路”的“救命稻草”?
    2022年中国车联网行业全景图谱
    2022年十大AI预测:气候独角兽涌现、中美竞争加剧
    OSEK/VDX介绍
    Adaptive Autosar
    基于我国商密算法的车联网5GV2X通信安全可信体系
    行研篇 | 汽车域控制器研究
  • 原文地址:https://www.cnblogs.com/remly/p/11225966.html
Copyright © 2011-2022 走看看