Decode Ways

2017-07-21  本文已影响7人  极速魔法

//91

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.

#include <iostream>
#include <vector>


using namespace std;
//similar to climbing stairs,dp[i-1] check s[i]!=0
//dp[i-2] check s[i-1]s[i] range 1-26
class Solution {
private:
    int validNum(char two,char one){
        //deal with input "01"
        if(two=='0'){
            return 0;
        }
        if(one=='0'){
            if(two>='3' || two=='0'){
                return 0;
            } else{
                return 1;
            }
        } else{
            if(two=='1' || (two=='2' && one<='6')){
                return 2;
            } else{
                return 1;
            }
        }

    }
public:
    int numDecodings(string s) {
        int size=s.size();
        if(size==0){
            return 0;
        }
        vector<int> dp(size,0);
        //init
        if(s[0] !='0'){
            dp[0]=1;
        }
        
       dp[1]=validNum(s[0],s[1]);
        
        for(int i=2;i<size;i++){
            if(s[i]!='0'){
                dp[i]+=dp[i-1];
            } 

            if((s[i-1]=='1' && s[i]>='0') || (s[i-1]=='2' && s[i]<='6')){
                dp[i]+=dp[i-2];
            }
        }

        return dp[size-1];
    }
};

int main(){
    string s="110";
    cout<<Solution().numDecodings(s);
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读