91 Decode Ways
'A' -> 1
'B' -> 2
...
'Z' -> 26class Solution:
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
# memoization
memo = {}
# helper DFS (preorder)
def __numDecodings(s, n):
# if the front string is empty return 1 (leaf node in tree)
if not s:
return 1
# check if in memory
elif s in memo:
return memo[s]
# otherwise perform recursion
else:
# only decend down tree if we can at least get empty string from s
result1, result2 = 0, 0
if n:
# car and cdr
front1 = s[0:n - 1]
tail1 = s[n - 1:]
# there is no way to interpret 0 as a valid answer
result1 = 0 if tail1 == '0' else __numDecodings(front1, n - 1)
if n-1:
# same idea, but now interpret 2 digits
front2 = s[0:n - 2]
tail2 = s[n - 2:]
# there is no way to interpret a valid solution if the
# number exceeds 26, or if the tail starts with 0 (consider edge case '101')
result2 = 0 if not (1 <= int(tail2) <= 26) or tail2[0] == '0' else __numDecodings(front2, n - 2)
memo[s] = result1 + result2
return memo[s]
return __numDecodings(s, len(s))Last updated


