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()
    }
    
  • 相关阅读:
    python并发编程
    中缀表达式转换为后缀表达式(python实现)
    使用docker部署filebeat和logstash
    数据结构和算法的一些思考
    RESTFUL如何指导WEB API设计?
    哈希表的原理及实现代码
    python实现有序字典
    django源码分析 请求流程
    python 通过元类控制类的创建
    前后端分离人力资源管理系统
  • 原文地址:https://www.cnblogs.com/mapoos/p/14193408.html
Copyright © 2011-2022 走看看