一条包含字母 A-Z 的消息通过以下方式进行了编码:
‘A’ -> 1
‘B’ -> 2
…
‘Z’ -> 26
给定一个只包含数字的非空字符串,请计算解码方法的总数。
递归
public int numDecodings(String s) {
int total = 0;
if (s.isEmpty()) {
return total;
}
String first = s.substring(0, 1);
if (0==Integer.valueOf(first)) {
return 0;
}
if (s.length() == 1) {
return 1;
}
int n = numDecodings(s.substring(1));
if (n>0) {
total += n;
}
first = s.substring(0, 2);
int x = Integer.valueOf(first);
if (x<=26) {
String y = s.substring(2);
if (y.isEmpty()) {
total += 1;
} else {
int t = numDecodings(y);
if (t>0) {
total += t;
}
}
}
return total;
}
动态规划
public int numDecodings(String s) {
if (s.isEmpty() || s.startsWith("0")) {
return 0;
}
int[] memo = new int[s.length()];
memo[0]=1;
if (s.length() > 1) {
Integer x = Integer.valueOf(s.substring(0,2));
if (s.charAt(1) == '0') {
if (x<27) {
memo[1] = 1;
} else {
memo[1] = 0;
}
} else {
if (x<27) {
memo[1] = 2;
} else {
memo[1] = 1;
}
}
}
for(int i=2;i<s.length();++i) {
String x = s.substring(i, i+1);
String y = s.substring(i-1, i+1);
if (x.equals("0")) {
if (y.equals("00")) {
memo[i]=0;
} else {
int k = Integer.valueOf(y);
if (k<27) {
memo[i] = memo[i-2];
} else {
memo[i]=0;
}
}
} else {
memo[i] = memo[i-1];
if(!y.startsWith("0")){
int k = Integer.valueOf(y);
if (k<27) {
memo[i] += memo[i-2];
}
}
}
}
return memo[s.length()-1];
}