639. Decode Ways II
Explanation
To solve this problem, we can use dynamic programming. We will iterate through the input string and calculate the number of ways to decode it based on the previous characters.
We will define two main dynamic programming arrays:
dp1[i]
represents the number of ways to decode the substrings.substring(0, i)
wheres[i]
is not a '*'.dp2[i]
represents the number of ways to decode the substrings.substring(0, i)
wheres[i]
is a '*'.
For each character in the input string:
- If
s[i]
is a digit from '1' to '9', we can updatedp1[i]
based on the previous characters. - If
s[i]
is '*', we can updatedp2[i]
based on the previous characters:- If
s[i-1]
is '1', '2', or '', we can have 9 possibilities for '' (mapping to '1' to '9'). - If
s[i-1]
is '0', we can have 6 possibilities for '*' (mapping to '1' to '6').
- If
The final answer will be the sum of dp1[n]
and dp2[n]
(where n
is the length of the input string).
class Solution {
public int numDecodings(String s) {
int n = s.length();
long MOD = 1000000007;
long[] dp1 = new long[n + 1];
long[] dp2 = new long[n + 1];
dp1[0] = 1;
dp2[0] = 0;
for (int i = 1; i <= n; i++) {
char c = s.charAt(i - 1);
if (c == '0') {
dp1[i] = 0;
dp2[i] = (dp2[i - 1] * 2) % MOD;
} else if (c == '*') {
dp1[i] = (dp1[i - 1] * 9 + dp2[i - 1] * 9) % MOD;
dp2[i] = (dp1[i - 1] + dp2[i - 1] * 6) % MOD;
} else {
dp1[i] = c == '0' ? 0 : dp1[i - 1];
dp2[i] = (dp1[i - 1] * (c > '6' ? 0 : 1) + dp2[i - 1] * (c > '6' ? 0 : 1)) % MOD;
}
}
return (int) ((dp1[n] + dp2[n]) % MOD);
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.