Decode Ways

来源:互联网 发布:穷人的生活 知乎 编辑:程序博客网 时间:2024/06/03 04:18

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.


Solution:

class Solution {public:    int numDecodings(string s) {        int len = s.length();        if(!len || s[0] == '0') return 0;        vector<int> dp(len);        dp[1] = dp[0] = 1;        if(s[0] > '2' && s[1] == '0') return 0;        if(s[0] == '1' && s[1] >= '1' && s[1] <= '9') dp[1] += 1;        if(s[0] == '2' && s[1] >= '1' && s[1] <= '6') dp[1] += 1;        for(int i = 2; i < len; ++i)        {            dp[i] = dp[i-1];            if(s[i] == '0')            {                if(s[i-1] == '1' || s[i-1] == '2')                {                    dp[i] = dp[i-2];                    continue;                }                else return 0;            }            if((s[i-1] == '1') || (s[i-1] == '2' && s[i] <= '6')) dp[i] += dp[i-2];        }                return dp[len-1];    }};


0 0
原创粉丝点击