Decode Ways

来源:互联网 发布:俄罗斯大卫知乎 编辑:程序博客网 时间:2024/06/02 16:10

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.

这些题目实现都没有考虑不合法的输入(non-num),考虑某个偏移i为止有多少种decode方式,会发现当前偏移i的方式取决于s[i] 和s[i - 1]的值以及偏移i - 1和i- 2时得到的decode的数目,所以这时一个一维的动态规划题目
如果s[i - 1]  == ‘1’ 或者 s[i - 1] == '2' && s[i] <= '6'  (这代表所有1*以及20 - 26),则当前的ret[i]  先要加上ret[i-2] (因为i-1 和i构成一个字母);
如果s[i]不为‘0’,则s[i]可以单独构成一个字母,所有ret[i]这时还要加上ret[i - 1]的数目。

code逻辑很简单,直接看代码就行。


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


0 0