Question:
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.
Solution:
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;
dp[1] = s.charAt(0) != '0' ? 1 : 0;
for(int i=2;i<=s.length();i++){
int first=Integer.valueOf(s.substring(i-1,i));
int second=Integer.valueOf(s.substring(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[0]为什么要等于1??因为遍历dp[3]的时候如果second是10~26的数那肯定是有一种组合可能的~所以dp[3]=dp[3-1]=1;