zoukankan      html  css  js  c++  java
  • Decode Ways

    A message containing letters from A-Z is being encoded to numbers using the following mapping:

    'A' -> 1
    'B' -> 2
    ...
    'Z' -> 26
    

    Given an encoded message containing digits, determine the total number of ways to decode it.

    For example,
    Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

    The number of ways decoding "12" is 2.

    Analyse: Let dp[i] is the decode ways of s[0...i-1].

      If last two characters XY is smaller than 26, XY could be decoded as X,Y or XY (do not consider 0 at this time). dp[i + 1] = dp[i - 1]  + dp[i], where dp[i - 1] is for X, Y and dp[i] is for XY. 

      If s[i] is '0', since the input is always valid, s[i -1] must be combined with s[i]. dp[i + 1] = dp[i]. Else if s[i] is not '0', dp[i + 1] = dp[i - 1] + dp[i + 1].  

    Runtime: 4ms. 

     1 class Solution {
     2 public:
     3     int numDecodings(string s) {
     4         if(s.empty() || s[0] < '1' || s[0] > '9') return 0;
     5         
     6         int n = s.size();
     7         vector<int> dp(n + 1, 0);
     8         dp[0] = dp[1] = 1;
     9         
    10         for(int i = 1; i < n; i++) {
    11             int lastTwo = (s[i - 1] - '0' ) * 10 + (s[i] - '0');
    12             if(lastTwo > 9 && lastTwo <= 26) dp[i + 1] += dp[i - 1];
    13             if(s[i] != '0') dp[i + 1] += dp[i];
    14         }
    15         return dp[n];
    16     }
    17 };
  • 相关阅读:
    dos常用命令
    组合封装知识点
    继承与派生知识点
    继承与派生
    面向对象知识点
    面向对象
    Day 84 DRF的分页和过滤
    Day80 使用第三方(腾讯云)短信验证码接口
    Day 79 xadmin后台管理/Git仓库
    Day 77 三大认证组件
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5745308.html
Copyright © 2011-2022 走看看