A message containing letters from
A simpler version, where extend dp[len] to dp[len+1] where dp[0] == 1 for empty string. As a result, i==1 is no longer a special case.
A-Z
is being encoded to numbers using the following mapping:
'A' -> 1 'B' -> 2 ... 'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12"
, it could be decoded as "AB"
(1 2) or "L"
(12).
The number of ways decoding "12"
is 2.
A typical DP problem. Neglect a special case: '100' should return 0;
My code:
public class Solution {
// DP: dp[i] = dp[i] + d[i-1]
public int numDecodings(String s) {
int len = s.length();
if(len == 0) return 0;
int[] dp = new int[len];
// dp[i] means the way to decode s[0~i]
if(s.charAt(0) == '0') return 0;
else dp[0] = 1;
int prev = s.charAt(0)-'0';
for(int i=1; i<len; i++){
int ch = s.charAt(i) - '0';
// case 1: ch as a new start
if(ch == 0){
if(prev == 0 || prev > 2) return 0;
else{ // prev == 1 or 2
if(i == 1) dp[i] = 1;
else dp[i] = dp[i-2];
}
}else{
dp[i] = dp[i-1];
int sum = prev*10 + ch;
if(sum <= 26 && prev != 0){
if(i == 1) dp[i] ++;
else dp[i] += dp[i-2];
}
}
prev = ch;
}
return dp[len-1];
}
}
A simpler version, where extend dp[len] to dp[len+1] where dp[0] == 1 for empty string. As a result, i==1 is no longer a special case.
public class Solution {
// DP: dp[i] = dp[i] + d[i-1]
public int numDecodings(String s) {
int len = s.length();
if(len == 0) return 0;
int[] dp = new int[len+1];
dp[0] = 1;
// dp[i] means the way to decode s[0~i]
if(s.charAt(0) == '0') return 0;
else dp[1] = 1;
int prev = s.charAt(0)-'0';
for(int i=2; i<=len; i++){
int ch = s.charAt(i-1) - '0';
// case 1: ch as a new start
if(ch == 0){
if(prev == 0 || prev > 2) return 0;
else{ // prev == 1 or 2
dp[i] = dp[i-2];
}
}else{
dp[i] = dp[i-1];
int sum = prev*10 + ch;
if(sum <= 26 && prev != 0){
dp[i] += dp[i-2];
}
}
prev = ch;
}
return dp[len];
}
}