标签:
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).
"12"
is 2.1 class Solution 2 { 3 public: 4 int numDecodings(string s) 5 { 6 if(s.empty() || s[0] == ‘0‘) return 0; 7 8 int f[s.size()]; 9 char pre = s[0], cur; 10 11 f[0] = 1; 12 f[1] = 1; 13 for(int i=2; i<=s.size(); i++) 14 { 15 cur = s[i-1]; 16 17 if(pre == ‘1‘ && cur != ‘0‘) 18 f[i] = f[i-1] + f[i-2]; 19 else if(pre == ‘2‘ && ‘1‘ <= cur && cur <= ‘6‘) 20 f[i] = f[i-1] + f[i-2]; 21 else if(cur == ‘0‘) 22 { 23 if(pre == ‘1‘ || pre == ‘2‘) 24 { 25 f[i-1] = f[i-2]; 26 f[i] = f[i-2]; 27 } 28 else 29 return 0; 30 } 31 else 32 f[i] = f[i-1]; 33 34 pre = cur; 35 } 36 37 return f[s.size()]; 38 } 39 };
标签:
原文地址:http://www.cnblogs.com/lxd2502/p/4251066.html