Decode Ways (M)
A message containing letters from A-Z
is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
题意
将’A’-'Z’这26个字母加密为整数1-26,判断一个只包含数字的字符串能够解密为多少个有效的字母字符串。
思路
试了一下回溯法,运行时间达到了691ms,非常的感人。转使用动态规划:
dp[i]表示以字符串中下标为i的字符为结尾的子字符串的有效解码个数。dp[i]初始为0。针对每个dp[i]做如下判断:当i处字符可以有效解码(即不为’0’)时, d p [ i ] + = d p [ i − 1 ] dp[i] += dp[i - 1] dp[i]+=dp[i−1];当i-1和i处字符组合起来能有效解码(即i-1处不为’0’且代表的数字在1-26之间)时, d p [ i ] + = d p [ i − 2 ] dp[i] += dp[i - 2] dp[i]+=dp[i−2]。
代码实现
class Solution {
public int numDecodings(String s) {
int dp[] = new int[s.length()];
dp[0] = s.charAt(0) == '0' ? 0 : 1;
for (int i = 1; i < s.length(); i++) {
int sum = (s.charAt(i - 1) - '0') * 10 + s.charAt(i) - '0';
if (s.charAt(i) != '0') {
dp[i] += dp[i - 1];
}
if (1 <= sum && sum <= 26 && s.charAt(i - 1) != '0') {
dp[i] += i >= 2 ? dp[i - 2] : 1; // 注意i=1时的特殊情况
}
}
return dp[s.length() - 1];
}
}