zoukankan      html  css  js  c++  java
  • Decode Ways

    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.

    类似于爬梯子,对于第i位,其解码方式可能为:

    1)如果该位不为0,则可以继续按照i-1位的方式解码

    2)如果该位和前一位的值在10和26之间,则可继续按照i-2位的方式解码

    class Solution {
    public:
        int numDecodings(string s) {
            
            if(s.empty())return 0;
            int len=s.size();
            vector<int> num(len+1,0);
            num[0]=1;
            
            for(int i=1;i<=len;i++)
            {
                if(s[i-1]!='0')
                   num[i]+=num[i-1];
                if(i>=2 && s.substr(i-2,2)>="10" && s.substr(i-2,2)<="26")
                   num[i]+=num[i-2];
            }
            
            return num.back();
        }
    };
    View Code
  • 相关阅读:
    Zabbix 3.2.1 安装 Graphtree3.0.4 或 Graphtree3.2.x
    jquery-1
    AngularJS (1)
    css-2 (Text Font)
    css
    Java经验
    js经验
    mysql经验
    MySQL 函数
    jquery 效果
  • 原文地址:https://www.cnblogs.com/573177885qq/p/6251447.html
Copyright © 2011-2022 走看看