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

 

转载于:https://www.cnblogs.com/remly/p/11225966.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值