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(因为加入了一个无关字符)

  • 相关阅读:
    Linux下Keepalived 安装与配置
    Nginx配置SSL证书部署HTTPS网站
    Nginx 实现MySQL的负载均衡
    iOS如何把导航默认的返回按钮设置成“返回”
    Java中JSON的简单使用与前端解析
    双机高可用、负载均衡、MySQL(读写分离、主从自动切换)架构设计
    iOS开发--使用RSA加密
    UIBezierPath画圆弧的记录
    SSL构建单双向https认证
    webpack配置上线地址
  • 原文地址:https://www.cnblogs.com/remly/p/11225966.html
Copyright © 2011-2022 走看看