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, 则有tmp[i] = tmp[i-1] + tmp[i-2]。但注意考虑"0*"的双字符情况。且初始边界条件也要注意,代码比较繁琐。
class Solution:
# @param s, a string
# @return an integer
def numDecodings(self, s):
if len(s) == 0:
return 0
if len(s) == 1:
if int(s) <= 0:
return 0
else:
return 1
tmp = [0 for x in range(len(s))]
if int(s[0]) != 0:
tmp[0] = 1
else:
tmp[0] = 0
if int(s[0:1]) > 26 and int(s[1]) == 0:
tmp[1] = 0
elif int(s[1]) == 0 and int(s[0:2]) <= 26:
tmp[1] = tmp[0]
elif int(s[1]) != 0 and int(s[0:2]) > 26:
tmp[1] = tmp[0]
elif int(s[1]) != 0 and int(s[0:2]) <= 26:
if s[0] == '0':
tmp[1] = 0
else:
tmp[1] = 2
for i in range(2,len(s)):
if int(s[i-1:i+1]) > 26 and int(s[i]) == 0:
tmp[i] = 0
elif int(s[i]) == 0 and int(s[i-1:i+1]) <= 26:
if s[i-1] == '0':
tmp[i] = 0
else:
tmp[i] = tmp[i-2]
elif int(s[i-1:i+1]) > 26 and int(s[i]) > 0:
tmp[i] = tmp[i-1]
else:
if s[i-1] == '0':
tmp[i] = tmp[i-1]
else:
tmp[i] = tmp[i-1] + tmp[i-2]
return tmp[len(s)-1]