91. Decode Ways(Python3)
题目
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message “12”, it could be decoded as “AB” (1 2) or “L” (12).
The number of ways decoding “12” is 2.
解题方案
思路:
- 动态规划题目,本质其实是斐波那契数列,但是由于0的存在导致了很多其他的可能性,主要是两点
- ‘0’必须和前面的‘1’或者‘2’结合才能有意义,否则就要直接返回0
- ‘0’不能与后面的数字结合
代码:
class Solution:
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if not s or s[0] == '0':
return 0
dp = [1,1]
for i in range(1,len(s)):
tmp = int(s[i-1:i+1])
if tmp >=1 and tmp <= 26 and s[i] == '0':
dp.append( dp[i-1] )
elif tmp >=1 and tmp <= 26 and s[i-1] != '0':
dp.append( dp[i] +dp[i-1] )
elif s[i] == '0':
return 0
else:
dp.append( dp[i] )
return dp[-1]
参考资料:http://blog.csdn.net/sunnyyoona/article/details/18703803