0091. Decode Ways¶
A message containing letters from A-Z
is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:
Input: s = "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: s = "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Example 3:
Input: s = "0"
Output: 0
Explanation: There is no character that is mapped to a number starting with '0'. We cannot ignore a zero when we face it while decoding. So, each '0' should be part of "10" --> 'J' or "20" --> 'T'.
Example 4:
Input: s = "1"
Output: 1
Constraints:
1 <= s.length <= 100
s
contains only digits and may contain leading zero(s).
java¶
public class Solution {
public int numDecodings(String s) {
if(s == null || s.length() == 0) {
return 0;
}
int n = s.length();
int[] dp = new int[n+1];
dp[0] = 1; // # of ways to decode for empty s
dp[1] = s.charAt(0) != '0' ? 1 : 0; // 0 cannot be leading element for a number
for(int i = 2; i <= n; i++) {
int first = Integer.valueOf(s.substring(i-1, i)); // s[i-1:i]
int second = Integer.valueOf(s.substring(i-2, i));// s[i-2:i]
if(first >= 1 && first <= 9) {
dp[i] += dp[i-1];
}
if(second >= 10 && second <= 26) {
dp[i] += dp[i-2];
}
}
return dp[n];
}
}
dp[i]
: number of ways to decode
dp[i] += dp[i-1]
ifs[i-1:i]
is valid (single digit: range from 0-9)dp[i] += dp[i-2]
ifs[i-2:i]
is valid (two digits: range from 10-26)
code¶
int numDecodings(string s) {
int n = s.size();
vector<int> dp(n+1);
dp[n] = 1;
for(int i = n - 1; ~i; i--) { // from back to front
if(s[i]=='0') dp[i]=0;
else {
dp[i] = dp[i+1];
if(i<n-1 && (s[i]=='1'||s[i]=='2'&&s[i+1]<'7')) dp[i]+=dp[i+2];
}
}
return s.empty()? 0 : dp[0];
}
dp[i] += dp[i+2]
if
1. s[i] == 1
, so that any s[i+2]
is valid, s[i:i+1]
is in range 10-19
2. s[i] == 2
and s[i+1] < 7
, so that s[i:i+1]
is in range 20-26
if s[i] == 0
, then dp[i] = 0
, because 0 cannot be leading
optimize with constant space¶
class Solution {
public:
int numDecodings(string s) {
int n = s.size();
int pre = 1, prepre = 1, curr = 1;
for(int i=n-1;i>=0;i--) { // from back to front
if(s[i]=='0') curr=0;
else {
curr=pre;
if(i<n-1 && (s[i]=='1'||s[i]=='2'&&s[i+1]<'7'))
curr+=prepre;
}
prepre = pre;
pre = curr;
curr = 1;
}
return s.empty()? 0 : pre;
}
};
only needs two more states from the current state, so
1. pre: s[i:i+1]
2. prepre: s[i:i+2]
Last update:
April 1, 2022