首页 > 其他 > 详细

[LeetCode] Decode Ways(DP)

时间:2014-08-13 12:38:26      阅读:345      评论:0      收藏:0      [点我收藏+]

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;
    
    }
};

 

[LeetCode] Decode Ways(DP),布布扣,bubuko.com

[LeetCode] Decode Ways(DP)

原文:http://www.cnblogs.com/Xylophone/p/3909556.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!