A catalog of data structures and problems with approaches to solve them
Given the mapping a = 1, b = 2, … z = 26, and an encoded message, count the number of ways it can be decoded.
For example, the message ‘111’ would give 3, since it could be decoded as ‘aaa’, ‘ka’, and ‘ak’.
You can assume that the messages are decodable. For example, ‘001’ is not allowed.
Let’s at some cases to build our approach:
We can use dynamic programming to cache computed steps for a string with one letter, two letters, three, all the way to the end of the string.
Our cache can contain zeros first.
cache[0] = 1.
Eventually after traversing the string, we’ll return the last element in our cache list, since it contains the total number of ways to decode the string.
def num_decodings(s) -> int:
cache = [0 for i in range(len(s))]
for i in range(len(s)):
if s[i].startswith('0'):
cache[i] = 0
elif i == 0:
cache[i] = 1
else:
num = int(s[i-1:i+1])
if num <= 26:
cache[i] = cache[i - 1] + 1
else:
cache[i] = cache[i - 1]
return cache[-1]
num_decodings("111")
3
num_decodings("1011") # (10, 11) and # (10, 1, 1) so 2 ways.
2