You have intercepted a secret message encoded as a string of numbers. The message is decoded via the following mapping:
"1" -> 'A' "2" -> 'B' ... "25" -> 'Y' "26" -> 'Z'
However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes ("2" and "5" vs "25").
For example, "11106" can be decoded into:
"AAJF"with the grouping(1, 1, 10, 6)"KJF"with the grouping(11, 10, 6)- The grouping
(1, 11, 06)is invalid because"06"is not a valid code (only"6"is valid).
Note: there may be strings that are impossible to decode.
Given a string s containing only digits, return the number of ways to decode it. If the entire string cannot be decoded in any valid way, return 0.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: s = “12”
Output: 2
Explanation:
“12” could be decoded as “AB” (1 2) or “L” (12).
Example 2:
Input: s = “226”
Output: 3
Explanation:
“226” could be decoded as “BZ” (2 26), “VF” (22 6), or “BBF” (2 2 6).
Example 3:
Input: s = “06”
Output: 0
Explanation:
“06” cannot be mapped to “F” because of the leading zero (“6” is different from “06”). In this case, the string is not a valid encoding, so return 0.
Constraints:
1 <= s.length <= 100scontains only digits and may contain leading zero(s).
Approach 1 - DP array
- First check the base case for empty string and return 0
- Then initialize array with n + 1 length which stores decode ways where at position n it stores decode ways
i -1 - initialize the zero and 1 index as 1 because to decode empty and just one length string it is only one way
- Then we just need to add for if let’s say 16 one way is 1 and 6 or take 16 as whole and then at final length
Time: O(n) Space: O(n)
class Solution {
public int numDecodings(String s) {
if (s.length() == 0 || s.charAt(0) == '0') {
return 0;
}
int[] dp = new int[s.length() + 1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= s.length(); i++) {
if (s.charAt(i-1) != '0') {
dp[i] += dp[i-1];
}
int t = Integer.parseInt(s.substring(i-2,i));
if (t >= 10 && t <= 26) {
dp[i] += dp[i-2];
}
}
return dp[s.length()];
}
}Approach 2 - Space optimization
- Use left and right pointer and do the same thing the difference being in above at
iyou get result fori-1but here right would be the exact solution so you can see the difference Time: O(n) Space: O(n)
class Solution {
public int numDecodings(String s) {
if (s.length() == 0 || s.charAt(0) == '0')
return 0;
int l = 1, r = 1;
for (int i = 1; i < s.length(); i++) {
int c = 0;
if (s.charAt(i) != '0') {
c += r;
}
int t = Integer.parseInt(s.substring(i-1,i+1));
if (t >= 10 && t <= 26) {
c += l;
}
l = r;
r = c;
}
return r;
}
}