其实本题和:http://www.geeksforgeeks.org/count-possible-decodings-given-digit-sequence/
是类似的。
但是这道题需要考虑错误情况。
1 class Solution { 2 public: 3 int numDecodings(string s) { 4 if(s == "") 5 return 0; 6 vector<int> count; 7 int i; 8 for(i = 0 ; i < s.length() ; ++i) 9 { 10 count.push_back(0); 11 if(s[i] < '0' || s[i] > '9') 12 return 0; 13 if(s[i] == '0') 14 { 15 if (i == 0 || s[i - 1] == '0' || s[i - 1] > '2') { 16 return 0; 17 } 18 else { 19 count[i] = i > 1 ? count[i - 2] : 1; 20 } 21 } 22 else 23 { 24 if(i == 0) 25 count[i] = 1; 26 else 27 { 28 if(s[i] > '0') 29 count[i] = count[i-1]; 30 if(i >= 1 &&(s[i-1] == '1' || (s[i-1] == '2' && s[i] < '7'))) 31 count[i] += i>1 ? count[i-2]:1; 32 } 33 } 34 } 35 return count[s.length()-1]; 36 } 37 };