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[C++]:
class Solution {
public:
int numDecodings(string s) {
int *a = new int[s.size()+1];
int i = 0;
a[0] = 0;
if ((s[0] - 48) != 0)
a[1] = 1;
else{
return 0;
}
if (s.size() >= 2){
if ((s[1] - 48) == 0){
if ((s[0] - 48) <= 2){
a[2] = 1;
if (s.size()>2){
if ((s[2]-48)== 0)
return 0;
else{
a[3] = a[2];
i = 4;
}
}
}
else{
return 0;
}
}
else if ( ((s[0] - 48) * 10 + (s[1] - 48)) > 26){
a[2] = 1;
}
else{
a[2] = 2;
}
}
if(i != 4){
i = 3;
}
for (; i <= s.size(); i++){
if ((s[i - 1] - 48) != 0 && ((s[i-2]-48)*10+(s[i-1]-48))<27){
a[i] = a[i - 2] + a[i - 1];
}
else if((s[i - 1] - 48) != 0 && (s[i - 1] - 48) != 0 && ((s[i-2]-48)*10+(s[i-1]-48))>=27){
a[i] = a[i-1];
}
else if ((s[i - 1] - 48) == 0 && ((s[i - 2] - 48) == 1 || (s[i - 2] - 48) == 2)){
a[i] = a[i - 2];
if ((i + 1) <= s.size() ){
if ((s[i]-48)== 0)
return 0;
else{
a[i + 1] = a[i];
i++;
}
}
}
else
return 0;
}
return a[s.size()];
}
};
本文介绍了一种将字母编码为数字的方法,并详细解释了如何计算给定数字串的不同解码方式总数。通过C++实现了解码算法,展示了具体的实现细节。
107

被折叠的 条评论
为什么被折叠?



