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.
class Solution {
public:int numDecodings(string s) {
int len = s.length();
if(len == 0){
return 0;
}
if(s[0] == '0'){
// first element should not be '0'
return 0;
}
if(len == 1){
return 1;
}
int fn_1 = 1;
int fn_2 = 1;
for(size_t i = 1; i < len; ++i){
int tmp = 0;
if(s[i] == '0'){
if(s[i-1] == '1' || (s[i-1] == '2' && s[i] <= '6') ){
tmp += fn_2;
}else{
return 0;
}
}else{
if(s[i-1] == '1' || (s[i-1] == '2' && s[i] <= '6') ){
tmp += (fn_1 + fn_2);
}else{
tmp += fn_1;
}
}
fn_2 = fn_1;
fn_1 = tmp;
}
return fn_1;
}
};