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
{
public:
int numDecodings(string s)
{
if (s.find("00") != string::npos || s[0] == '0' || s.empty())
return 0;
if (s.size() == 1) return 1;
int prev2 = 1;
int prev1 = 0;
if (atoi(s.substr(0, 2).c_str()) <= 26)
prev1++;
if (s[1] != '0')
prev1++;
for (int i = 2; i < s.length(); i++)
{
int tmp = 0;
if (s[i] == '0')
{
if (s[i-1] > '2')
return 0;
}
else
tmp = prev1;
if (s[i - 1] != '0' && atoi(s.substr(i-1, 2).c_str()) <= 26)
tmp += prev2;
prev2 = prev1;
prev1 = tmp;
}
return prev1;
}
};