0091. Decode Ways (M)

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')时,\(dp[i] += dp[i - 1]\);当i-1和i处字符组合起来能有效解码(即i-1处不为'0'且代表的数字在1-26之间)时,\(dp[i] += dp[i - 2]\)


代码实现

Java

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];
    }
}

JavaScript

/**
 * @param {string} s
 * @return {number}
 */
var numDecodings = function (s) {
  let dp = new Array(s.length).fill(0)
  dp[0] = s[0] === '0' ? 0 : 1

  for (let i = 1; i < s.length; i++) {
    let sum = s[i - 1] * 10 + +s[i]
    if (s[i] !== '0') {
      dp[i] = dp[i - 1]
    }
    if (sum >= 1 && sum <= 26 && s[i - 1] !== '0') {
      dp[i] += i > 1 ? dp[i - 2] : 1
    }
  }

  return dp.pop()
}
posted @ 2020-12-26 16:57  墨云黑  阅读(57)  评论(0编辑  收藏  举报