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.
分析:
这道题目基本上来说是一个非常简单的动态规划,但是,有很多需要注意的边界条件,其主要的问题在于0的处理,题目可以理解成当存在时输出可能组合数,不存在时输出0. 然后,所以数字都要有组合,要用到,这对于0来说尤其重要! 当有0时,它必须要和前面一个数结合,一旦结合不成功,就没有组合可能。 对于其他的数字,考虑跟他前面一个数字的结合性,成功则 S[i] = S[i-1]+S[i-2]; 否则 S[i]=S[i-1];
1 class Solution { 2 public: 3 int numDecodings(string s) { 4 if(s.empty() || s[0]=='0') return 0; 5 vector<int> rec(s.size(),0); 6 7 stringstream stoi; 8 string trans; 9 rec[0] = 1; 10 int num; 11 for(int i=1;i<s.size();i++) 12 { 13 if(s[i]=='0') 14 { 15 if(s[i-1]>'0' && s[i-1]<'3') 16 { 17 if(i-2<0) rec[i] = 1; 18 else rec[i] = rec[i-2]; 19 continue; 20 } 21 else return 0; 22 } 23 trans.clear(); 24 trans.push_back(s[i - 1]); 25 trans.push_back(s[i]); 26 stoi<<trans; 27 stoi>>num; 28 stoi.clear(); 29 if(num<10 || num>26) 30 { 31 rec[i] = rec[i-1]; 32 continue; 33 } 34 else{ 35 if(i-2<0) rec[i] = rec[i-1]+1; 36 else rec[i] = rec[i-1]+rec[i-2]; 37 } 38 39 40 41 } 42 return rec[s.size()-1]; 43 } 44 };