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];
    }
};
原文地址:https://www.cnblogs.com/willwu/p/6086952.html