91. The decoding method
Message that includes the letters AZ is encoded by:
'A' ->. 1
'B' -> 2
...
'the Z' -> 26 is
determined to contain only non-empty string of numbers, calculate the total number of the decoding method.
Example 1:
Input: "12"
Output: 2
explanation: It may be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226"
Output: 3
explain: it can be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6) .
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' ? 0 : 1);
for(int i=1; i<n; i++) {
char c = s.charAt(i);
char pre = s.charAt(i-1);
dp[i+1] = c == '0' ? 0 : dp[i];
if(pre == '1' || (pre == '2' && c <= '6')) {
dp[i+1] += dp[i-1];
}
}
return dp[n];
}
}