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.
斐波那契数,在注意出现0的情况去除,以及俩个数不超过26的情况。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int numDecodings(string s) ;
int main()
{
string s;
cin>>s;
cout<<numDecodings(s)<<endl;
return 0;
}
int numDecodings(string s)
{
if(s.empty()) return 0;
vector<int> dp(s.size()+1);//统计总数,从0开始
dp[0] = 1;
if(s[0] != '0')
{
dp[1] = 1;
}
else
{
dp[1] = 0;
}
for(int i = 2;i <= s.size();i++)
{
if(s[i-2] != '0'&&s[i-1]!= '0'&&((s[i-2]=='1')||(s[i-2] == '2'&&s[i-1] <= '6')))
{
dp[i] = dp[i-1]+dp[i-2];
}
else if(s[i-1]== '0')//当前为0,
{
if(s[i-2]!= '0' && s[i-2] <= '2' )// 前一个不为0且小于2
{
dp[i] = dp[i-2];
}
else// 俩个都为0
{
dp[i] = 0;
}
}
else// s[i-2] == 0.
{
dp[i] = dp[i-1];
}
}
return dp[s.size()];
}