strings
dynamic-programming
A message was encoded using the mapping 1 -> A, 2 -> B, ..., 26 -> Z. Given a string of digits, return how many different ways it can be decoded. A leading zero is never valid by itself, and two-digit decodings are only allowed for values from 10 through 26.
Input / output
- Input:
s: stringcontaining only digits - Output: integer number of valid decodings
Examples
s = "12"returns2because it can be decoded asABorL.s = "226"returns3because the valid decodings areBZ,VF, andBBF.s = "06"returns0because no decoding may start with0.
Constraints
1 <= s.length <= 100scontains only digits
Target complexity
- Aim for
O(n)time andO(1)extra space.
Hints
- Let
dp[i]mean: how many ways can the suffix starting at indexibe decoded? - At each position, you may use one digit, and sometimes also two digits, if that pair is between
10and26.
Follow-up
How would the recurrence change if the encoding also allowed * to mean any digit from 1 to 9?
Examples
Example 1
Input: s = "12"
Output: 2
Example 2
Input: s = "226"
Output: 3
Example 3
Input: s = "06"
Output: 0
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.