The dynamic programming approach leverages the fact that a problem can be broken into subproblems. Here, we use an array dp where dp[i] represents the number of ways to decode the substring s[0..i-1].
We iterate through the string and update the dp array based on the valid single and two-digit mappings.
Time Complexity: O(n)
, where n is the length of the input string. This is because we iterate over each character once.
Space Complexity: O(n)
, as we use an additional array of size n for storing our results for subproblems.
1var numDecodings = function(s) {
2 if (!s || s[0] === '0') return 0;
3 let n = s.length;
4 let dp = Array(n + 1).fill(0);
5 dp[0] = 1;
6 dp[1] = 1;
7
8 for (let i = 2; i <= n; i++) {
9 let oneDigit = parseInt(s.substring(i - 1, i));
10 let twoDigits = parseInt(s.substring(i - 2, i));
11
12 if (oneDigit >= 1) {
13 dp[i] += dp[i - 1];
14 }
15 if (twoDigits >= 10 && twoDigits <= 26) {
16 dp[i] += dp[i - 2];
17 }
18 }
19 return dp[n];
20};
JavaScript's solution leverages arrays, slice operations, and parseInt for character manipulation, considering single and two-character possibilities sequentially.
It manages an array similarly to establish counts of valid decodings observed at any index level.
Instead of using an entire array to store all previous results, this approach keeps track of only the last two computations (since we only ever need the last two values for our dp computations).
Thus, we use two variables to hold these values and update them as needed to keep our space usage minimal.
Time Complexity: O(n)
, since each character in the string is touched once.
Space Complexity: O(1)
, because only two variables are used to maintain state.
1public class Solution {
2 public int numDecodings(String s) {
3 if (s == null || s.length() == 0 || s.charAt(0) == '0') return 0;
4
5 int n = s.length();
6 int prev1 = 1, prev2 = 1;
7
8 for (int i = 1; i < n; i++) {
9 int current = 0;
10 int oneDigit = Integer.parseInt(s.substring(i, i + 1));
11 int twoDigits = Integer.parseInt(s.substring(i - 1, i + 1));
12
13 if (oneDigit >= 1) {
14 current += prev1;
15 }
16 if (twoDigits >= 10 && twoDigits <= 26) {
17 current += prev2;
18 }
19 prev2 = prev1;
20 prev1 = current;
21 }
22
23 return prev1;
24 }
25}
Java's approach exemplifies using a minimalist strategy of two variables to hold interim computation results, sequentially updating as iteration advances.
This precludes heavy memory use while maintaining both results needed for further calculations.