• 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

     

  • 相关阅读:
    Java_基础_内存管理
    Reflux中文教程——action
    Reflux中文教程——概览
    包含块、层叠上下文、BFC
    DOM编程的性能问题
    JavaScript数据存取的性能问题
    闭包
    JavaScript中的继承
    JavaScript中的静态成员
    JavaScript中的私有属性
  • 原文地址:https://www.cnblogs.com/fu11211129/p/5017876.html
Copyright © 2020-2023  润新知