Difficulty: 3
Frequency: 4
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.
Solution:
class Solution {
public:
int numDecodings(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s.size()==0||s[0]=='0')// Subtlety 1
return 0;
vector<int> decode_method(s.size()+1);
decode_method[0] = 1;
decode_method[1] = 1;
for (int i = 1; i<s.size(); i++)
{
if (s[i]=='0')
{
if (s[i-1]=='0'||s[i-1]>'2')// Subtlety 2
return 0;
decode_method[i+1] = decode_method[i-1];
}
else
{
switch(s[i-1]){// Subtlety 3
case '1':
decode_method[i+1] = decode_method[i] + decode_method[i-1];
break;
case '2':
if (s[i]<='6'&&s[i]>='0')
decode_method[i+1] = decode_method[i] + decode_method[i-1];
else
decode_method[i+1] = decode_method[i];
break;
default:
decode_method[i+1] = decode_method[i];
break;
}
}
}
return decode_method[s.size()];
}
};
Notes:
Kinda like Fibonacci numbers. But there are lots of special cases should be pay attention to.