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.
一维DP问题,类似于Restore IP Addresses,只是这个问题更简单了,只需要考虑个位和十位数字。
public static int numDecodings(String s){
if(s.isEmpty()) return 0;
int[] dp = new int[s.length()];
for(int i = 0; i < dp.length; i++) dp[i]=-1;
return numDecodingsHelper(s,0,dp);
}
private static int numDecodingsHelper(String s, int i , int[] dp){
if(i == s.length()) return 1;
if(dp[i] != -1) return dp[i];
int first=0, second = 0;
if(i+1 <= s.length() && s.charAt(i)!='0')
first = numDecodingsHelper(s,i+1,dp);
if(i+2 <= s.length() && s.charAt(i)!='0' && Integer.valueOf(s.substring(i,i+2))<=26)
second = numDecodingsHelper(s,i+2,dp);
dp[i] = first + second;
return dp[i];
}