A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it.
For example, Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
tag:
- dp
满足最优子结构和子问题重叠, 采用动态规划算法:
设f[i]
表示字串长度为i的解码方式数量,f[0]=0
, 则:
设f[i]=0
最后一位字符作为一个编码(s.charAt(i-1)>'0'
): f[i] += f[i-1]
最后两位字符作为一个编码(i>1 且 "10"=<s[i-2]s[i-1]<="26"
): f[i] += f[i-2]
代码如下:
java
public int numDecodings(String s) {
int length = s.length();
if (length == 0)
return 0;
int[] res = new int[length + 1];
res[0] = 1;
for (int i = 1; i <= length; i++) {
if (s.charAt(i-1) > '0')
res[i] += res[i-1];
if (i>1 && Integer.parseInt(s.substring(i - 2, i)) >= 10 && Integer.parseInt(s.substring(i - 2, i)) <= 26)
res[i] += res[i - 2];
}
return res[length];
}
go