首页 > 代码库 > [LeetCode] Decode Ways(DP)

[LeetCode] Decode Ways(DP)

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的出现

class Solution {public:    int numDecodings(string s) {        int len = s.size();        if(len==0)            return 0;        vector<int> num(len,0);//第i个位置记录从s的第0个位置开始到第i个位置共有几种解码方式        if(len>=1 && s[0]==0)                 return 0;                num[0] = 1;        if(len==1)            return num[0];                    string s0 = s.substr(0,2);        int d  = sToInt(s0);        int n=0;        if(d>10 && d<=26 &&  d!=20)            num[1] = 2;        else if((s[1] ==0 && (s[0]==1|| s[0]==2))||s[1]!=0)            num[1] = num[0];        else            return 0;                        for(int i=2;i<len;i++){            if(s[i-1]==0){                if(s[i]!=0){                    num[i] = num[i-1];                    continue;                }                else                    return 0;            }                    s0 = s.substr(i-1,2);            d  = sToInt(s0);            if(s[i]==0){                if(d==10 || d==20){                   num[i] = num[i-2];                   continue;                }                                  else                    return 0;            }                        if(d>10 && d<=26 )                num[i] = num[i-1]+num[i-2];            else                num[i] = num[i-1];                        }//end for        return num[len-1];    }private:    int sToInt(string s){      istringstream is(s);      int d;      is>>d;      return d;        }};