Problem
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).
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
Algorithm
Let num[i] = number of ways to decode the string ending at S[i].
num[i] = num[i-1] if S[i] has valid decoding
num[i-2] + num[i-1] if both S[i] and S[i-1 to i] have valid decoding
If 1<= S[i] <= 9, it is valid
If S[i-1] = 1, 0 <= S[i] <= 9, it is valid
If S[i-1] = 2, 0 <= S[i] <= 6, it is valid
Others are not valid
Boundary condition, L[0] = 0, if S[0] = 0
No comments:
Post a Comment