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 {
int fibnacci_sum(int n)
{
if (n == 0)
return 1;
if (n == 1)
return 1;
if (n == 2)
return 2;
return fibnacci_sum(n - 1) + fibnacci_sum(n - 2);
}
public:
int numDecodings(string s) {
if (s.empty())
return 0;
if (s.length() == 1)
{
if (s[0] != '0')
return 1;
return 0;
}
int k = 0;
int nums = 1;
while (k + 1 < s.length())
{
if (s[0] == '0')
return 0;
k = 0;
while (k + 1 < s.length())
{
if (s[k] >= '3')
{
nums *= fibnacci_sum(k+1);
s.erase(0, k + 1);
k = 0;
break;
}
if (s[k] == '0')
{
nums *= fibnacci_sum(k - 1);
s.erase(0, k + 1);
k = 0;
break;
}
if (s[k] == '2'&&s[k + 1] > '6')
{
nums *= fibnacci_sum(k + 1);
s.erase(0, k + 1);
k = 0;
break;
}
k++;
}
}
if (s.length() > 1)
{
if (s[k] >= '3')
nums *= fibnacci_sum(k+1);
else if (s[k] == '0')
nums *= fibnacci_sum(k - 1);
else
nums *= fibnacci_sum(s.length());
return nums;
}
if (s.empty())
return nums;
if (s[0] == '0')
return 0;
return nums;
}
};
accepted

本文介绍了一种用于解码数字字符串的算法,该算法能够计算出一个由A到Z字母组成的编码消息的所有可能解码方式的数量。例如,对于编码消息12,它可以被解码为AB或L,因此解码方式总数为2。
2041

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



