Problem Description
Given a string s that consists of digits and the '*' wildcard character (which represents any digit from '1' to '9'), determine the number of ways to decode it. Each digit or pair of digits (with valid mapping 'A' = 1 to 'Z' = 26) can be mapped back to a letter. The answer should be computed modulo 10^9 + 7.
Key Insights
- Use dynamic programming where dp[i] represents the number of ways to decode the substring up to index i.
- Process one-character and two-character decoding possibilities separately.
- Carefully handle '*' characters; they can represent 9 possibilities on their own, but when forming two-digit numbers, combinations vary based on the digit they pair with.
- Optimize space by only keeping track of the last two dp state values.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1), using constant space by tracking only the last two dp values.
Solution
The solution is based on dynamic programming. We iterate over the string while maintaining two variables (dp0 and dp1) that represent the number of decoding ways for the substring ending at the previous two positions. For each character, we process:
- Single-digit decoding: If the current character is '*' it contributes 9 ways; if it is a non-'0' digit, it contributes 1 way.
- Two-digit decoding: The number of ways depends on the previous character and current character, and special handling is required when either or both are ''. For instance, if the previous character is '' and current is '', there are 15 valid combinations (from treating '' as '1' or '2'). Finally, we update our dp state while applying modulo arithmetic.