zoukankan      html  css  js  c++  java
  • leetcode@ [91] Decode Ways (Dynamic Programming)

    https://leetcode.com/problems/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.

     

    class Solution {
    public:
        bool check(char a, char b) {
            int na = a - '0', nb = b - '0';
            if(na == 0) return false;
            if(na*10 + nb >= 1 && na*10 + nb <= 26) return true;
            return false;
        }
        int numDecodings(string s) {
            if(s.length() == 0) return 0;
            
            vector<int> dp(s.length(), 0);
            dp[0] = (s[0]=='0')? 0: 1;
            if(s.length() == 1) return dp[0];
            
            if(dp[0] == 0) return 0;
            else {
                bool flag = check(s[0], s[1]);
                if(s[1] == '0' && flag) dp[1] = 1;
                else if(s[1] == '0' && !flag) return 0;
                else if(s[1] != '0' && flag) dp[1] = 2;
                else if(s[1] != '0' && !flag) dp[1] = 1;
            }
            
            for(int i=2;i<s.length();++i) {
                if(s[i] == '0') {
                    if(check(s[i-1], s[i])) dp[i] = dp[i-2];
                    else return 0;
                }
                else {
                    if(check(s[i-1], s[i])) dp[i] = dp[i-1] + dp[i-2];
                    else dp[i] = dp[i-1];
                }
            }
            
            return dp[s.length()-1];
        }
    };
    leetcode 91: Decode Ways

     

  • 相关阅读:
    shell脚本100例、练习使用
    shell基础编程
    mysql基础理论知识
    Docker 基础
    python基础之类(面向对象编程)
    python基础之函数
    python基础之认知及编码
    python基础之数据类型
    python基础之注意事项
    1.linux使用基础
  • 原文地址:https://www.cnblogs.com/fu11211129/p/5017876.html
Copyright © 2011-2022 走看看