A message containing letters from 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.
Analysis: this is also a dynamic programming problem: we just need to decide how many conditions there to get the numbres.
1 if the char is '0',
2 if the char is from '1' to '6'
3 if the char is from '7' to '9'
and then based on the conditions above to decide how to decode the string.
public class Solution {
public int numDecodings(String s) {
int length = s.length();
if(length <= 0)
return 0;
int[] dp = new int[length + 1];
dp[0] = 1;
dp[1] = 1;
//this is a corner case.
char tem = s.charAt(0);
if(tem == '0')
return 0;
for(int i = 2; i <= length; i++){
char temChar = s.charAt(i - 1);
if(temChar == '0')
{
char pre = s.charAt(i - 2);
if(pre - '1' == 0 || pre - '1' == 1)
dp[i] = dp[i - 2];
else
return 0;
}
else if(temChar - '1' >= 0 && temChar - '6' <= 0 )
{
char pre = s.charAt(i - 2);
if(pre - '1' == 0 || pre - '1' == 1)
dp[i] = dp[i - 2] + dp[i - 1];
else
dp[i] = dp[i - 1];
}
else{
char pre = s.charAt(i - 2);
if(pre - '1' == 0)
dp[i] = dp[i - 2] + dp[i - 1];
else
dp[i] = dp[i - 1];
}
}
return dp[length];
}
}