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.
Subscribe to see which companies asked this question.
编码问题,给一个数字组成的字符串,求可能的字母构成个数
坑很多,主要还是0的情况;
首位为0直接去,若存在30、100这种情况直接return 0,所以一开始先遍历一遍字符串排除这种干扰;
动态规划~
sum[i]----->前i位可能的个数
先弄出1位2位的情况:
几种情况:
s[i - 1] > '2' || s[i - 1] == '0' || (s[i - 1] == '2' && s[i] > '6')
s[i] == '0'
代码如下:
class Solution {
public:
int numDecodings(string s) {
if(s.size() == 0)
return 0;
if (s[0] == '0')
return 0;
if(s.size() == 1)
return 1;
for (int i = 1 ; i < s.size() ; i ++)//判断输入有没有无效的比如30,100这种
{
if (s[i] == '0')
{
if(s[i - 1] != '2' && s[i - 1] != '1')
return 0;
}
}
if(s.size() == 2)
{
if(s[0] > '2' || (s[0] == '2' && s[1] > '6'))
return 1;
else if(s[1] == '0')
return 1;
else
return 2;
}
int sum[s.size()] = {0};
sum[0] = 1;
if (s[0] > '2' || (s[0] == '2' && s[1] > '6'))
sum[1] = 1;
else if (s[1] == '0')
sum[1] = 1;
else
sum[1] = 2;
for (int i = 2 ; i < s.size(); i ++)
{
if(s[i - 1] > '2' || s[i - 1] == '0' || (s[i - 1] == '2' && s[i] > '6'))
sum[i] = sum[i - 1];
else if(s[i] == '0')
sum[i] = sum[i - 2];
else
sum[i] = sum[i - 1] + sum[i -2];
}
return sum[s.size() - 1];
}
};