91. Decode Ways
Description
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.
Analysis
这道题的意思就是让我们求所给字符串有多少种可能的组合。
我的做法是新建一个数组res,而且数组的程度比字符串多1。res[i]表示表示当前s[i-1]可能的组合数。
显示当s[i-1]=0时,就说明必定是要与前一个数字进行组合,所以s[i-1]!=0时,res[i] = res[i-1。然后在通过判断和前一个数字的组合是否超过26,如果没有超过26,就 res[i]+=res[i-2]。
最后返回结果。
Code
class Solution {
public:
int numDecodings(string s) {
if(s.size() == 0) return 0;
if(s[0] == '0') return 0;
int len = s.size();
int res[len+1];
res[0] = 1;
res[1] = 1;
for(int i = 2; i<len+1;++i ){
if(s[i-1] != '0' ) res[i] = res[i-1];
else res[i] = 0;
if(s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <='6')) res[i]+=res[i-2];
}
return res[len];
}
};