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.
1:特殊情况的考虑:第一个字符为0;2:从前到后遍历字符串,如果当前字符是‘0’的时候,只考虑与前一个字符编码成为一个符号;2:如果当前字符不为‘0’的时候,当前字符可以编码,以及考虑与前面一个字符是否可以编码成一种字符
int numDecodings(string s)
{
if(s.empty() || (s.size() == 1 && s[0] == '0'))
{
return 0;
}
unsigned long size = s.size();
int* A = new int[size];
A[0] = (s[0] == '0' ? 0 : 1);
for(int i = 1; s[i] != '\0'; i++)
{
if(s[i] != '0')
{
A[i] = A[i-1];
}
else
{
A[i] = 0;
}
if((s[i] >= '0' && s[i] <= '9' && s[i-1] == '1') || (s[i] >= '0' && s[i] <= '6' && s[i-1] == '2'))
{
if(i-1 == 0)
{
A[i] += 1;
}
else
{
A[i] += A[i-2];
}
}
}
return A[size-1];
}