Problem:
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:
This can be solved by dynamic programming. A new string of length n can be viewed as either a string of length (n-1) plus a new character or a string of length (n-1) plus two new characters. Why only these two ways? Because the longest code of Letter is "26" of length 2. Then the answer a_n can be constructed with the answer of a_{n-1} and a_{n-2}.
For a_{n-1}, the new character must be valid which means it can't be 0. it can expressed as (ch=='0' ? 0 : a_{n-1})
For a_{n-2}, the new sub-string must be valid which means it shou be in the range of 10~26. else return 0;
The initialization should be pay enough attention, the above inductive process requires the current character is 3. So for string of length 0, 1, or 2, we directly compute them.
For string of length 3 or longer, we use the induction. With the initial a_{n-1} and a_{n-2} set to proper values.
a_{n-2} = s[0] == '0' ? 0 : 1;
a_{n-1} = isValid(s[0], s[1], 2) + (isValid(s[0], 1) && isValid(s[1], 1))
Notice the initialization of a_{n-1};
The running time is O(n) and the space needed is O(1).
Code:
1 class Solution { 2 public: 3 int numDecodings(string s) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (s.length() == 0) 7 return 0; 8 else if (s.length() == 1) 9 return ck1(s[0], 1); 10 else if (s.length() == 2) { 11 int cnt = 0; 12 if (ck1(s[0], 1) && ck1(s[1], 1)) 13 cnt++; 14 15 return cnt + ck2(s[0], s[1], 1); 16 } 17 18 int an2 = ck1(s[0], 1), an1 = ck2(s[0], s[1], 1), an; 19 if (ck1(s[0], 1) && ck1(s[1], 1)) 20 an1++; 21 22 for (int i=2; i<s.length(); i++) { 23 an = ck1(s[i], an1) + ck2(s[i-1], s[i], an2); 24 25 an2 = an1; 26 an1 = an; 27 } 28 29 return an; 30 } 31 32 int ck1(char c, int n) { 33 return (c == '0') ? 0 : n; 34 } 35 36 int ck2(char c1, char c2, int n) { 37 if(c1 == '1' || (c1 == '2' && (c2>='0' && c2 <= '6'))) 38 return n; 39 else 40 return 0; 41 } 42 };