• Decode Ways


    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.

    分析:简单的动态规划套路,注意一下字符串中0的处理,比如“10”只能一种情况,而“1001”则根本不存在解

    class Solution {
    public:
        int numDecodings(string s) {
             if(s.size()==0)
                return 0;
             int len = s.size();
             vector<int> dp(len+1,0);
             dp[0] = 1;
             if(s[0]!='0')
               dp[1] = 1;
            
             for(int i=2;i<=len; i++){
                if(s[i-1]-'0'>0)
                    dp[i] += dp[i-1];
                 string t = s.substr(i-2,2);
                 if(stoi(t)<=26 && stoi(t)>0 && s[i-2]!='0')
                    dp[i] +=dp[i-2];
                 cout << "i = "<< i<<" "<< dp[i]<<endl;
             }
             return dp[len];
        }
    };
  • 相关阅读:
    pexpect模块
    Python正则表达式
    telnetlib
    paramiko
    threadpool和Queue
    logging
    Python异常
    Python迭代器
    程序员工资那么高,却从不炫富?网友回复让人“笑喷了”!
    小白到web前端工程师需要学习哪些知识?
  • 原文地址:https://www.cnblogs.com/willwu/p/6086952.html
Copyright © 2020-2023  润新知