题目说明
一条包含字母 A-Z 的消息通过以下方式进行了编码:
‘A’ -> 1
‘B’ -> 2
…
‘Z’ -> 26
给定一个只包含数字的非空字符串,请计算解码方法的总数。
输入: “12”
输出: 2
解释: 它可以解码为 “AB”(1 2)或者 “L”(12)
本题比较坑的测试用例:
“10”-----------------------1
“27”-----------------------1
“00”-----------------------0
“01”-----------------------0
“101”-----------------------1
“110”-----------------------1
“230”-----------------------0
“27”-----------------------1
“12120”-----------------------3
“7206”-----------------------1
“1212”-----------------------5
链接:https://leetcode-cn.com/problems/decode-ways
int numDecodings(string s)
{
vector<int> res(s.size() + 1, 0);
if (s.size() == 0)
return 0;
if (s[0] - '0' == 0)
return 0;
res[0] = 1;
res[1] = 1;
for (int i = 2; i <= s.size(); i++)
{
if (s[i - 1] != '0')
{
res[i] += res[i - 1];
}
if (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))
{
res[i] += res[i - 2];
}
}
return res[s.size()];
}