首页 > 其他 > 详细

[LeetCode] Decode Ways

时间:2015-03-28 15:49:57      阅读:189      评论:0      收藏:0      [点我收藏+]

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.

解题思路:
动态规划。这种题目分两种情况讨论。若最后一个字符与前一个字符联合编码(且符合条件),则d[i]+=d[i-2]。若最后一个字符单独编码(且符合条件),则d[i] += d[i-1]。发现自己动态规划很不熟悉,分析问题的亟待提高啊。
class Solution {
public:
    int numDecodings(string s) {
        int len = s.length();
        if(len == 0){
            return 0;
        }
        int* d = new int[len + 1];  //表示前i个字符有d[i - 1]中解码方式
        d[0] = 1; //0个字符的情况通过分析1、2个字符情况得知
        if(check(s[0])){
            d[1] = 1;
        }else{
            d[1] = 0;
        }
        for(int i = 1; i < len; i++){
            d[i + 1] = 0;
            if(check(s[i-1], s[i])){
                d[i+1] += d[i -1];
            }
            if(check(s[i])){
                d[i+1] += d[i];
            }
        }
        int result = d[len];
        delete[] d;
        return result;
    }
private:
    bool check(char c){
        if(c == '0'){
            return false;
        }else{
            return true;
        }
    }
    bool check(char c1, char c2){
        if(c1 == '0' || c1 > '2' || (c1=='2' && c2 > '6' )){
            return false;
        }else{
            return true;
        }
    }
};


[LeetCode] Decode Ways

原文:http://blog.csdn.net/kangrydotnet/article/details/44701239

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