13. Dcode Message
This problem was asked by Facebook.
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.
分析情況
If string starts with zero, then there's no valid encoding.
If the string's length is less than or equal to 1, there is only 1 encoding.
If the first two digits form a number
k
that is less than or equal to 26, we can recursively count the number of encodings assuming we pickk
as a letter.We can also pick the first digit as a letter and count the number of encodings with this assumption.
def decodeWays(msg):
return r_decodeWays(msg, 0)
def r_decodeWays(msg, count):
# 考慮msg長度=3的情況
if len(msg) == 3:
count = 0
addCount = True
# 1. 每個char都不能為0
for c in msg:
if int(c) == 0:
addCount = False
if addCount: count += 1
# 2. 將長度切成2,1
a = int(msg[0:2])
b = int(msg[2:])
if a >= 10 and a <= 26 and b > 0:
count += 1
# 3. 將長度切成1,2
a = int(msg[0:1])
b = int(msg[1:])
if a > 0 and b >= 10 and b <= 26:
count += 1
return count
else:
return r_decodeWays(msg[:3], count) + r_decodeWays(msg[3:], count)
Time: O(2^n)
TODO: 遞迴算法的時間分析
Last updated
Was this helpful?