首页 > 其他 > 详细

leetcode@ [91] Decode Ways (Dynamic Programming)

时间:2015-12-03 23:18:15      阅读:413      评论:0      收藏:0      [点我收藏+]

https://leetcode.com/problems/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) {
        int na = a - ‘0‘, nb = b - ‘0‘;
        if(na == 0) return false;
        if(na*10 + nb >= 1 && na*10 + nb <= 26) return true;
        return false;
    }
    int numDecodings(string s) {
        if(s.length() == 0) return 0;
        
        vector<int> dp(s.length(), 0);
        dp[0] = (s[0]==‘0‘)? 0: 1;
        if(s.length() == 1) return dp[0];
        
        if(dp[0] == 0) return 0;
        else {
            bool flag = check(s[0], s[1]);
            if(s[1] == ‘0‘ && flag) dp[1] = 1;
            else if(s[1] == ‘0‘ && !flag) return 0;
            else if(s[1] != ‘0‘ && flag) dp[1] = 2;
            else if(s[1] != ‘0‘ && !flag) dp[1] = 1;
        }
        
        for(int i=2;i<s.length();++i) {
            if(s[i] == ‘0‘) {
                if(check(s[i-1], s[i])) dp[i] = dp[i-2];
                else return 0;
            }
            else {
                if(check(s[i-1], s[i])) dp[i] = dp[i-1] + dp[i-2];
                else dp[i] = dp[i-1];
            }
        }
        
        return dp[s.length()-1];
    }
};
leetcode 91: Decode Ways

 

leetcode@ [91] Decode Ways (Dynamic Programming)

原文:http://www.cnblogs.com/fu11211129/p/5017876.html

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