码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode——91.解码方法

时间:2019-10-15 12:54:01      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:color   class   info   结果   def   python3   内存   span   ==   

class Solution:
    def numDecodings(self, s: str) -> int:
        a={}
        if int(s[0])==0:
            return 0
        else:
            a[0]=1
        if len(s)==1:
            return a[0]
        if int(s[0])>2 and int(s[1])==0:
            a[1]=0
            if len(s)>1:
                return 0
        if (int(s[0]+s[1])>26) or (int(s[0])<3 and int(s[1])==0):
            a[1]=1
        elif int(s[0]+s[1])<=26:
            a[1]=2
        #print(a)
        if len(s)==2:
            return a[1]
        for i in range(2,len(s)):
            if s[i-1]==0 and s[i]==0:
                return 0
            elif int(s[i-1])>2 and s[i]==0:
                return 0
            elif (int(s[i-1]+s[i]))>26 or (s[i-1]==0 and int(s[i])!=0):
                a[i]=a[i-1]
            elif int(s[i-1])<3 and s[i]==0:
                a[i]=a[i-2]
            elif int(s[i-1]+s[i])<=26:
                a[i]=a[i-1]+a[i-2]
            else:
                a[i]=a[i-1]
        return a[len(s)-1]
执行用时 :44 ms, 在所有 python3 提交中击败了88.37%的用户
内存消耗 :14 MB, 在所有 python3 提交中击败了5.21%的用户
 
思路分析:
当字符串的首位为0的时候,直接输出0;
先分析给定前两位的种类个数,统一分析长度大于2的情况;
如果中间位出现30,40,50等等的这种情况以及00的这种情况,直接输出0;
如果像31,58这种大于26的数,输出结果与前一位的结果相同,即a[i]=a[i-1];
如果像02,03,09这种情况,a[i]=a[i-1];
如果是10,20这样的情况,a[i]=a[i-2]
如果是23,18等这种小于27的情况,a[i]=a[i-1]+a[i-2]
结束。
 
 
                                                              ——2019.10.15

leetcode——91.解码方法

标签:color   class   info   结果   def   python3   内存   span   ==   

原文地址:https://www.cnblogs.com/taoyuxin/p/11676790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!