LeetCode 639: Decode Ways II Solution
Master LeetCode problem 639 (Decode Ways II), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
639. Decode Ways II
Problem Explanation
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).
Solution Code
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);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 639 (Decode Ways II)?
This page provides optimized solutions for LeetCode problem 639 (Decode Ways II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 639 (Decode Ways II)?
The time complexity for LeetCode 639 (Decode Ways II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 639 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 639 in Java, C++, or Python.