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.
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[] dp = new int[n + 1];
7 dp[0] = 1;
8 dp[1] = 1;
9
10 for (int i = 2; i <= n; i++) {
11 int oneDigit = Integer.parseInt(s.substring(i - 1, i));
12 int twoDigits = Integer.parseInt(s.substring(i - 2, i));
13
14 if (oneDigit >= 1) {
15 dp[i] += dp[i - 1];
16 }
17 if (twoDigits >= 10 && twoDigits <= 26) {
18 dp[i] += dp[i - 2];
19 }
20 }
21 return dp[n];
22 }
23}
The Java version utilizes substring and parseInt functions to extract single and two-digit numbers from the string. The dp array in this solution behaves similarly, recording upfront possibilities for decodings.
Utilizing two substring operations helps simplify reading digits in different lengths.
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.
1#include <string.h>
2
3int numDecodings(char * s) {
4 if (s[0] == '0') return 0;
5 int n = strlen(s), prev2 = 1, prev1 = 1;
6
7 for (int i = 2; i <= n; i++) {
8 int current = 0;
9 int oneDigit = s[i - 1] - '0';
10 int twoDigits = (s[i - 2] - '0') * 10 + oneDigit;
11
12 if (oneDigit >= 1) {
13 current += prev1;
14 }
15 if (twoDigits >= 10 && twoDigits <= 26) {
16 current += prev2;
17 }
18 prev2 = prev1;
19 prev1 = current;
20 }
21 return prev1;
22}
This C solution reduces space complexity by using two variables - prev1
and prev2
to keep track of decodings without maintaining a full dp array.
These variables capture prior computations needed for the current index advance.