标签:
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.
1 class Solution { 2 public: 3 int numDecodings(string s) { 4 if(s.empty() || s[0] ==‘0‘) return 0; 5 int len=s.length(); 6 if(len==1) return check(s[0]); 7 int fn=0, fn1, fn2; 8 fn1 = check(s[0]); 9 fn2 = check(s[0], s[1]); 10 for(int i=1; i< s.size(); i++) 11 { 12 if(check(s[i])) fn+= fn1; 13 if(check(s[i-1], s[i])) fn+=fn2; 14 if(fn ==0) 15 return 0; 16 fn2 = fn1; 17 fn1 = fn; 18 fn=0; 19 } 20 return fn1; 21 } 22 int check(char one) 23 { 24 return (one != ‘0‘) ? 1 : 0; 25 } 26 int check(char one, char two) 27 { 28 return (one == ‘1‘ || (one == ‘2‘ && two <= ‘6‘)) 29 ? 1 : 0; 30 } 31 };
标签:
原文地址:http://www.cnblogs.com/hexhxy/p/5567263.html