LeetCode_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.

  动态规划: 

class Solution {

public:

    bool check(char a, char b){

        if(a == '1')

            return true;

        if(a == '2' && b>= '0' && b<= '6')

            return true;

        return false;

    }

    int numDecodings(string s) {

        int len = s.size();

        if(len == 0 || s[0] == '0') return 0;

        vector<int> res(len+1,0);

        res[0] = 1;

        res[1] = 1;

        for(int i = 1; i < len ; ++i){

            if(s[i] == '0' && (s[i-1] == 0||s[i-1]>'2'))

                return 0;

            if(s[i]<='9'&& s[i] > '0')

              res[i+1] = res[i];

            if(check(s[i-1], s[i]))

                res[i+1] += res[i-1];

        }

        

        return res[len];

    }

};

 

你可能感兴趣的:(LeetCode)