Decode Ways
Last updated
def decode_ways(s):
n = len(s)
if n == 1: return 1
s1, s2 = 1, 0 # s1 -> dp(i+1), s2 -> dp(i+2)
for i in range(n - 1, -1, -1):
si = 0 if s[i] == '0' else s1 # equivalent to collapsing the first 3 cases
if i < n - 1 and (s[i] == '1' or (s[i] == '2' and s[i + 1] <= '6')):
si += s2
s1, s2 = si, s1
return s1