算法设计Week14 LeetCode Algorithms Problem #91 Decode Ways

来源:互联网 发布:mac浏览器chrome 编辑:程序博客网 时间:2024/06/05 03:07

题目描述:

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.


题目分析:

使用动态规划算法,如果使用count[i]来表示到s[i]字符对应的解码方式的话,考虑增加一个字符s[i]时,如果它与前一个字符(s[i - 1])能构成两位(即10-26)的编码的话,则count[i] = count[i - 1] + count[i - 2]。而如果不能,则count[i] = count[i - 1]。
在实际解题的过程中,发现LeetCode上的输入并不全是合法的,也就是说,输入会有类似’40’,’100’的无法解码输入。对于0,只需要考虑它前一位是否是1或2,如果是的话,那么count[i] = count[i - 2];反之,则没有解码方法,也即0。
算法的时间复杂度为O(n),空间复杂度为O(n)


解法代码:

class Solution {public:    int numDecodings(string s) {        int length = s.size();        if(length == 0 || s[0] == '0') return 0;        // 方便编码,count[i + 1]对应s[i]        vector<int> count(length + 1, 0);          count[0] = 1;        count[1] = 1;        for(int i = 1; i < length; i++){            if(s[i] != '0'){                if(s[i - 1] == '1' || (s[i - 1] == '2' && s[i] <= '6')){                    count[i + 1] = count[i] + count[i - 1];                }                else{                    count[i + 1] = count[i];                }            }else{  // s[i]为0时要特殊考虑                if(s[i - 1] == '1' || s[i - 1] == '2')                    count[i + 1] = count[i - 1];                else                    return 0;            }        }        return count[length];    }};
原创粉丝点击