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.
题意:一段密文由以下对应关系生成,若给定一条密文,求密文还原为原文的可能方式
‘A’ -> 1
‘B’ -> 2
…
‘Z’ -> 26
例如密文12,就会被解码为AB或L
解题思路:动态规划,在解码过程中,假设此时解码长度为k,则当前解码的方式受长度k-1,k-2的密文影响,即dp[k] = dp[k - 1] + dp[k - 2],此时从i-2到i的子密文代表的数字应该小于等于26;否则dp[k] = dp[k - 1]
代码:
public class Solution {
public int numDecodings(String s) {
int n = s.length();
if (n == 0) return 0;
int[] memo = new int[n+1];
memo[n] = 1;
memo[n-1] = s.charAt(n-1) != '0' ? 1 : 0;
for (int i = n - 2; i >= 0; i--)
if (s.charAt(i) == '0') continue;
else memo[i] = (Integer.parseInt(s.substring(i,i+2))<=26) ? memo[i+1]+memo[i+2] : memo[i+1];
return memo[0];
}
}