package com.algorithm.dynamicprogramming;
/**
* 算法描述:包含A-Z字母的消息正在使用以下映射编码为数字: ‘A’->1 ‘B’->2 ... ‘Z’->26
* 给定一个只包含数字的非空字符串,确定解码该字符串的方法总数。
* Example 1:
* Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L"
* Example 2:
* Input: "226" Output: 3 Explanation: It could be decoded as "BZ" (2 26), "VF"
* (22 6), or "BBF" (2 2 6).
*
* @author rich
*
*/
public class DecodeWays {
public static void main(String[] args) {
System.out.println(decodeWays("226"));
}
public static int decodeWays(String digit) {
if (digit == null || digit.length() == 0) {
return 0;
}
int[] memo = new int[digit.length() + 1];
memo[0] = 1; // 初始化 为1
memo[1] = digit.charAt(0) == '0' ? 0 : 1; // 当首字母为0时有0个
for (int i = 2; i <= digit.length(); i++) {
if (digit.charAt(i - 1) == '0') { // 前一个字母为0
if (digit.charAt(i - 2) == '1' || digit.charAt(i - 2) == '2') { // 前两个等于1或2
memo[i] = memo[i - 2];
} else {
memo[i] = 0;
}
} else {
if (digit.charAt(i - 2) == '1' || (digit.charAt(i - 2) == '2' && digit.charAt(i - 1) <= '6')) {
memo[i] = memo[i - 1] + memo[i - 2];
} else {
memo[i] = memo[i - 1];
}
}
}
return memo[digit.length()];
}
}