leetcode 91 解码方法
z

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

1
2
3
4
'A' -> 1
'B' -> 2
...
'Z' -> 26

给定一个只包含数字的非空字符串,请计算解码方法的总数。

示例 1:

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

示例 2:

1
2
3
输入: "226"
输出: 3
解释: 它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
cnt = 0
if not s:
return 0
dp = [0] * (len(s)+1)
dp[-1] = 1
for i in range(len(s)-1, -1, -1):
if s[i] == '0':
continue
dp[i] = dp[i+1]
if s[i] != '0' and i+2 <= len(s) and 10<=int(s[i:i+2])<= 26:
dp[i] += dp[i+2]
return dp[0]