zoukankan      html  css  js  c++  java
  • 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()
    }
    
  • 相关阅读:
    Git for Windows之基础环境搭建与基础操作
    TFS2018环境搭建一单实例安装(适用于小型团队)
    TFS2018环境搭建一硬件要求
    Proxy代理模式(结构型模式)
    Flyweight享元模式(结构型模式)
    Facade外观模式(结构性模式)
    Decorator装饰者模式(结构型模式)
    Composite组合模式(结构型模式)
    mybatis中 #{} 和 ${} 的区别
    解决mybatis中#{}导致的The error may involve defaultParameterMap的问题
  • 原文地址:https://www.cnblogs.com/mapoos/p/14193408.html
Copyright © 2011-2022 走看看