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.
Code:
class Solution {
public:
int numDecodings(string s) {
if(s.empty()) return 0;
int len = s.length();
for(int i = 0; i < len; i ++)
//if 0 is the start,or a there is a digit>2 in front of a 0, this cannot be decoded
if(s[i] == '0' && i==0 || s[i] == '0' && (s[i-1] !='1' &&s[i-1]!='2'))
return 0;
int dp[len] = {0};//dp[i] represents the number of decoding ways starting for s[i...end]
dp[len-1] = 1;
for(int i = len-2; i >=0; i --){
if(s[i] == '1'){
dp[i] = dp[i+1];
if(i+1 < len && s[i+1]!='0'){//if its next is not 0,
if(i+2 < len && s[i+2]!='0') //if its next next is not 0, then 1 and its next can form a digit < 26.
dp[i] += dp[i+2];
if(i+2 == len) dp[i]++;//if its next next is the end, then it could has only 1 extra dway
}
}else if(s[i] == '2'){
dp[i] = dp[i+1];
if(i+1 < len && s[i+1]!='0' && s[i+1] <= '6'){//if its next is not 0 and its next is less than 6, then it possibly forms another digit with its next
if(i+2 <len && s[i+2] != '0') dp[i] += dp[i+2];//if its next next is not 0 then it could form a digit with its next
if(i+2 == len) dp[i]++;//if its next next is the end, then it could only has 1 extra way.
}
}else
dp[i] = dp[i+1];//if this number is > 2, it could not form any other digits with its next
}
return dp[0];
}
}