• 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()
    }
    
  • 相关阅读:
    Java 位运算(移位、位与、或、异或、非)
    解决Android Studio 2.2.3中添加.cpp .h文件在Project->Android无法显示,无法正常编译问题。
    [ACM] HDU 5083 Instruction (模拟)
    Vbox视图热键
    Android Drawable 与 LayerList综合汇总
    数学之路-python计算实战(14)-机器视觉-图像增强(直方图均衡化)
    HDU 2896 病毒侵袭 AC自己主动机题解
    对团队中“这是某某某的问题”引起的思考
    杭电 2201
    三层架构
  • 原文地址:https://www.cnblogs.com/mapoos/p/14193408.html
Copyright © 2020-2023  润新知