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 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.
题意
就上面最后一段那个意思
思路
这道题仍然是求true or false, 首先想到dp。这道题还是和青蛙跳台阶蛮相似的,但是难点要分情况考虑了,每次拿两个字符出来,一共三种情况,11-26(除了10),10和20,以及其他。注意dp[i]为以i为结尾的字符串解码方式数量的总和(就像青蛙跳台阶一样)
python实现
class Solution:
def numDecodings(self, s):
n = len(s)
if s == "" or s[0] == '0':
return 0
# 初始化1,1
dp = [1, 1]
for i in range(2, n + 1):
if 11 <= int(s[i - 2:i]) <= 26 and s[i - 1] != '0':
dp.append(dp[i - 1] + dp[i - 2])
elif (s[i - 2] == '1' or s[i - 2] == '2') and s[i - 1] != '0':
dp.append(dp[i - 2])
else:
dp.append(dp[i - 1])
return dp[n]