题目
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.
答案
class Solution {
public int numDecodings(String s) {
if(s.equals("")) return 0;
int[] dp = new int[s.length() + 1];
dp[s.length() - 1] = s.charAt(s.length() - 1) != '0' ? 1:0;
dp[s.length()] = 1;
for(int i = s.length() - 2; i >= 0; i--) {
String t = s.substring(i, i + 2);
int n = Integer.parseInt(t);
dp[i] = ((t.charAt(0) != '0') ? dp[i+1]:0) + ((n > 0 && n <= 26 && t.charAt(0) != '0')? dp[i + 2]:0);
}
return dp[0];
}
}
class Solution {
public int numDecodings(String ss) {
if(ss.equals("")) return 0;
char[] s = ss.toCharArray();
int n = s.length;
int[] f = new int[n + 1];
f[0] = 1;
for(int i = 1; i <= n; i++) {
f[i] = 0;
if(s[i - 1] >= '1' && s[i - 1] <= '9')
f[i] += f[i - 1];
if(i > 1) {
int j = 10 * (s[i - 2] - '0') + (s[i - 1] - '0');
if(j >= 10 && j <= 26)
f[i] += f[i - 2];
}
}
return f[n];
}
}