• 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
  • 相关阅读:
    Many Equal Substrings CF
    Seek the Name, Seek the Fame POJ
    人人都是好朋友(离散化 + 并查集)
    建设道路
    day_30
    day_29作业
    day_29
    day_28
    day_27
    day_26作业
  • 原文地址:https://www.cnblogs.com/573177885qq/p/6251447.html
Copyright © 2020-2023  润新知