题目为LeetCode 第 91 题,一条包含字母 A-Z 的消息通过以下方式进行了编码:
'A' -> 1
'B' -> 2
…
'Z' -> 26
给定一个只包含数字的非空字符串,计算解码方法的总数。
该题可用递归来解决,直接贴代码:
public static int numDecodings(String s) {
if (s.charAt(0) == '0') return 0; char[] chars = s.toCharArray(); return decode(chars, chars.length - 1); }
// 字符串转换成字符数组,利用递归函数 decode,从最后一个字符向前递归
private int decode(char[] chars, int index) { // 如果下标为0,说明处理到了字符串头部, if (index <= 0) {
return 1;
}
int count = 0; char curr = chars[index]; char prev = chars[index - 1]; // 当前字符比 “0” 大,则直接利用它之前的字符串所求得的结果 if (curr > '0') { count = decode(chars, index - 1); } //组成字符的数字为两位,需要判断数字是否在1-26之间 if (prev == '1' || (prev == '2' && curr <= '6')) { count += decode(chars, index - 2); } return count; }
扫描二维码关注公众号,回复:
7950083 查看本文章