码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Decode Ways(DP)

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

标签:style   blog   color   io   for   div   amp   log   

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)

标签:style   blog   color   io   for   div   amp   log   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!