leetcode 91. 解码方法

一条包含字母 A-Z 的消息通过以下方式进行了编码:

'A' -> 1
'B' -> 2
...
'Z' -> 26
给定一个只包含数字的非空字符串,请计算解码方法的总数。

示例 1:

输入: "12"
输出: 2
解释: 它可以解码为 "AB"(1 2)或者 "L"(12)。
示例 2:

输入: "226"
输出: 3
解释: 它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/decode-ways
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

count[i]:子串[0-i]的解码总数。

 1 public int numDecodings(String s) {
 2         if (s.charAt(0)=='0') return 0;
 3         // 用这个只能击败15.53%的人,用13行能击败94.98%的人,这差距。。。
 4         // if (Pattern.matches("(.*)0{2}(.*)",s)) return 0;
 5         // count[i]: 子串[0-i]的解码总数
 6         int[] count = new int[s.length()];
 7         int cnt;
 8         count[0] = 1;
 9         for (int i = 1; i < s.length(); ++i){
10             cnt = 0;
11             if (s.charAt(i)=='0' && s.charAt(i-1)>'2')
12                 return 0;
13             if (s.charAt(i)=='0' && s.charAt(i-1)=='0') return 0;
14             if (s.charAt(i-1) == '1' || (s.charAt(i-1) == '2' && s.charAt(i) <= '6')) {
15                 // i位置单占一个
16                 if (s.charAt(i) != '0')
17                     cnt += count[i-1];
18 
19                 // i位置与前一个化为一组
20                 cnt += (i-2 < 0) ? 1 : count[i-2]; //(count[i-2] == 0) ? 1 : count[i-2];
21             } else {
22                 cnt += count[i-1];
23             }
24             count[i] = cnt;
25         }
26         return count[s.length()-1];
27     }