[Problem]
S[i:n] = S[i+1:n] + S[i+2:n],即,i~n的字符串可以将i单独解码,也可以将i和i+1联合解码,S[i:n]表示字符串i~n的解码种数。
注意:单独解码时,0是不能被解码的。
[Solution]
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.
S[i:n] = S[i+1:n] + S[i+2:n],即,i~n的字符串可以将i单独解码,也可以将i和i+1联合解码,S[i:n]表示字符串i~n的解码种数。
注意:单独解码时,0是不能被解码的。
[Solution]
class Solution {说明:版权所有,转载请注明出处。 Coder007的博客
public:
// if the string could be decoded as a character
bool canBeDecoded(string s){
// invalid string
if(s.size() <= 0 || s.size() > 2)return false;
// 1 ~ 9
if(s.size() == 1 && s[0] >= '1' && s[0] <= '9')return true;
// two digits
if(s.size() == 2){
// 10 ~ 19
if(s[0] == '1' && s[1] >= '0' && s[1] <= '9')return true;
// 20 ~ 26
if(s[0] == '2' && s[1] >= '0' && s[1] <= '6')return true;
}
return false;
}
// get the number of decoding ways of the string
int numDecodings(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// empty string
if(s.size() == 0)return 0;
// if the s is valid: all characters are digit
for(int i = 0; i < s.size(); ++i){
if(!(s[i] >= '0' && s[i] <= '9'))return 0;
}
// decode
int count[s.size()];
memset(count, 0, sizeof(count));
for(int i = s.size()-1; i >= 0; --i){
// decoded as itself
if(s[i] > '0'){
if(i+1 >= s.size()){
count[i] += 1;
}
else if(count[i+1] > 0){
count[i] += count[i+1];
}
}
// decoded with the next character
if(i+1 < s.size() && canBeDecoded(s.substr(i, 2))){
if(i+2 >= s.size()){
count[i] += 1;
}
else if(count[i+2] > 0){
count[i] += count[i+2];
}
}
}
return count[0];
}
};