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 };
  • 相关阅读:
    Codeforces Round #239(Div. 2) 做后扯淡玩
    hdu 3507 Print Article
    prufer序列
    POJ 2778 DNA Sequence
    Codeforces Round #237 (Div. 2)
    poj3352
    图论知识
    POJ 2186
    Codeforces Round #236 (Div. 2)
    POJ 2823 Sliding Window
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5745308.html
Copyright © 2011-2022 走看看