Problem:
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.
Java Code:
public class Solution {
public int numDecodings(String s) {
//state: f[i] the number of decodings in s.substring(0, i)
//f[i] = f[i - 1] + f[i - 2](if i >= 2 && decodable(s.substring(i - 1, i + 1)))
if (s == null || s.length() == 0) {
return 0;
}
int[] dp = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
int num2 = 0;
if (i >= 1 && Integer.parseInt(s.substring(i - 1, i + 1)) <= 26
&& Integer.parseInt(s.substring(i - 1, i + 1)) >= 10) {
num2 = i >= 2 ? dp[i - 2] : 1;
}
int num1 = 0;
if (Integer.parseInt(s.substring(i, i + 1)) >= 1) {
num1 = i >= 1 ? dp[i - 1] : 1;
}
if (num1 == 0 && num2 == 0) {
return 0;
} else {
dp[i] = num1 + num2;
}
}
return dp[s.length() - 1];
}
}
没有评论:
发表评论