1.题目
有一个消息包含A-Z
通过以下规则编码
'A' -> 1
'B' -> 2
...
'Z' -> 26
现在给你一个加密过后的消息,问有几种解码的方式
12
,有两种方式解码 AB(12) 或者 L(12). 所以返回
2
2.算法
这道题是动态规划的题目,如果我们知道前i-1个数字有res[i-1]种方式,如果第i个数字可单独表示字字母,则res[i]=res[i-1],如果可以和前一个数字表示则res[i]=res[i-2],递推表达式为
(1)00:res[i]=0(无法解析,没有可行解析方式);
(2)10, 20:res[i]=res[i-2](只有第二种情况成立);
(3)11-19, 21-26:res[i]=res[i-1]+res[i-2](两种情况都可行);
(4)01-09, 27-99:res[i]=res[i-1](只有第一种情况可行);
public int numDecodings(String s) {
// Write your code here
if (s == null || s.length() == 0 || s.charAt(0) == '0') {
return 0;
}
int num1 = 1;
int num2 = 1;
int num3 = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == '0') {
if (s.charAt(i - 1) == '1' || s.charAt(i - 1) == '2') {
num3 = num1;
} else {
return 0;
}
} else {
if (s.charAt(i - 1) == '0' || s.charAt(i - 1) >= '3') {
num3 = num2;
} else {
if (s.charAt(i - 1) == '2' && s.charAt(i) >= '7' && s.charAt(i) <= '9') {
num3 = num2;
} else {
num3 = num2 + num1;
}
}
}
num1 = num2;
num2 = num3;
}
return num2;
}
原帖http://blog.csdn.net/linhuanmars/article/details/24570759