A message containing letters fromA-Zis 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:
bool ok(char c1, char c2)
{
if(c1 == '1')
{
if(c2 >= '0' && c2 <= '9')
return true;
}
else if(c1 == '2')
{
if(c2 >= '0' && c2 <= '6')
return true;
}
return false;
}
int numDecodings(string s)
{
int n = s.size();
if(n == 0)
return 0;
if(s[0] == '0')
return 0;
vector<int> dp(n+1, 0);
dp[0] = 1;
dp[1] = 1;
for(int i=2; i<=n; i++)
{
dp[i] = dp[i-1] + (ok(s[i-2], s[i-1]) ? dp[i-2]: 0);
if(s[i-1] == '0')
dp[i] = dp[i-2];
if(s[i-1] == '0' && (s[i-2] != '1' && s[i-2] != '2'))
dp[i] = 0;
}
return dp[n];
}
};