leetcode刷题-91解码方法

题目

一条包含字母 A-Z 的消息通过以下方式进行了编码:

'A' -> 1
'B' -> 2
...
'Z' -> 26
给定一个只包含数字的非空字符串,请计算解码方法的总数。

示例 1:

输入: "12"
输出: 2
解释: 它可以解码为 "AB"(1 2)或者 "L"(12)。

思路

这道题和70题爬楼梯非常类似,需要使用动态规划的方法

实现

class Solution:
    def numDecodings(self, s: str) -> int:
        l = len(s)
        if l==0: return 0
        num = [0 for i in range(l)]
        num[0] = 1 if s[0]!='0' else 0
        if l > 1:
            num[1] = 1 if s[0:2]>='10' and s[0:2]<='26' else 0
        for i in range(1,l):
            if s[i] != '0':
                num[i] += num[i-1]
            if s[i-1:i+1]>='10' and s[i-1:i+1]<='26' and i>=2:
                num[i] += num[i-2]
        return num[-1]

 

posted @ 2020-08-13 17:28  maoguai  阅读(140)  评论(0编辑  收藏  举报