91. Decode Ways
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226"
Output: 3
E 26), "VF" (22 6), or "BBF" (2 2 6).ded as “BZ” (2 26), “VF” (22 6),
or “BBF” (2 2 6).xplanation: It could be decoded a`s "BZ" (2
First
类似于台阶问题,当两个数字组成小于26且大于10时。字符串s[:i]的所有可能解码方式等于s[:i-1]+s[:i-2].
使用dp数组存储中间值,定义dp[i]为从0到i之间的所有解码方式, 则dp[i] = dp[i-1] + dp[i-2]
此外,我们还需要对0值进行处理
- 当字符s[i]等于'0',且'0'的前面一位大于'2'。比如'30',因为'30'无法编码,所以返回0。
- 当字符s[i]等于'0',但前面一位小于'2'时,则只能让'0'和前面一位进行编码,因此可能方式等于dp[i-2]。
- 当字符s[i-1]等于'0'时,由于'0'只能跟s[i-2]的字符匹配解码,因此s[i]只能选择单独解码或和s[i+1]共同解码
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
if s and s[0] == "0":
return 0
dp = [1 for _ in range(len(s))]
for i in range(1, len(s)):
if s[i] == '0':
if s[i-1: i+1] > '27' or s[i-1] == '0':
return 0
else:
dp[i] = dp[i - 2]
elif s[i-1: i+1] < '10':
dp[i] = dp[i - 2]
elif s[i-1: i+1] < '27':
dp[i] = dp[i-1] + dp[i-2]
else:
dp[i] = dp[i-1]
return dp[-1]
s = Solution()
print(s.numDecodings(''))
网友评论