LeetCode题解 week9

来源:互联网 发布:苹果7开数据的快捷 编辑:程序博客网 时间:2024/06/11 14:09

T91 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.

已知‘A’编码为1,‘B’编码为2,…,‘Z’编码为26,那么,给一串数字,求出一共有多少种译码方式。

在译码过程中,产生歧义的数字为‘11’~‘19’,‘21’~‘26’,比如‘11’可以理解为‘1’和‘1’即译为‘AA’或者是译为‘K’,需要注意的是‘0’这个数字,由于编码是从0开始而不是从1开始,所以‘0’单独编码,必须和前面一位数字组合起来,组成‘10’(G)或者‘20’(T),才能成功译码,所以我们也可以注意到,若是这串需要译码的数字由‘0’开头,或者是‘0’前面的数字不是‘1’或者‘2’,则是一条无效的消息。

这道题我们可以使用动态规划的思想。
s表示输入的数字串,result[i]表示s的前i个数字串组成的子数字串的译码方式数。
首先初始化result数组,result[0] = 1,result[1] = 1(当s只有一位的时候,只有一种译码方式)。
若s[i]独自可以译码成一个字母(‘1’~‘9’),且s[i-1]和s[i]组成的数字也能译成一个字母(‘11’~‘26’),那么总译码方式格式result[i] = result[i-1](独自译码的译码种数)+result[i-2](组合译码的译码种数)。
若s[i]为‘0’,那么它只能和前面一个数字组合译码,如果能组成‘10’或者‘20’,result[i] = result[i-2],否则为无效的错误消息,return 0。
若s[i]可以独自译码,但是与前一个数字不能组合译码(>‘26’),那么译码方式数result[i] = result[i-1]。
使用一个循环,对每个子数字串进行计算后,result的最后一位即为我们想要的结果。

以下为参考代码:
注:由于result[1]对应s[0],所以result与s的下标实际上有1的差。

class Solution {public:    int numDecodings(string s) {        int len = s.length();        if(len == 0 || s[0] == '0')            return 0;        if(len == 1)            return 1;        int result[len+1];        result[0] = 1;        result[1] = 1;        for(int i = 1; i < len; i++) {            if(s[i] != '0' && canCombine(s[i-1], s[i]))                result[i+1] = result[i] + result[i-1];            if(s[i] == '0' && canCombine(s[i-1], s[i]))                result[i+1] = result[i-1];            if(s[i] != '0' && !canCombine(s[i-1], s[i]))                result[i+1] = result[i];            if(s[i] == '0' && !canCombine(s[i-1], s[i]))                return 0;        }        return result[len];    }    bool canCombine(char a, char b) {        if(a == '1')            return true;        if(a == '2' && b >= '0' && b <= '6')            return true;        return false;    }};