A message containing letters from A-Z
is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6)
算法解析:
首先如果第 i 位出现‘0’ , 如果第 i - 1 位 为 ‘1’,‘2’, 则dp[ i ] = dp[ i - 2]
如果第 i 位 出现 ‘1’ ~ ‘6’ , 如果第 i - 1 位 为 ‘ 2’,则 dp[ i ] = dp[ i - 1] + dp[ i - 2]
如果第 i 位 出现 ‘1’ ~ ‘9’ , 如果第 i - 1 位 为 ‘1 ’, 则 dp[ i ] = dp [i - 1] + dp[ i - 2]
否则,dp[ i ] = dp [ i - 1]
同时注意数组不要越界 -1, - 2
代码如下:
class Solution {
public:
int numDecodings(string s) {
int len = s.length();
if(len == 0)
return 0;
vector<int> dp(len,0);
if(s[0] == '0') return 0;
dp[0] = 1;
for(int i = 1; i < len; i++)
{
if(s[i] == '0')
{
if(s[i-1] > '0' && s[i - 1] <= '2')
{
if(i < 2)
{
dp[i] = 1;
}
else
{
dp[i] = dp[i - 2];
}
}
else
return 0;
}
else if(s[i] > '0' && s[i] <= '6' && s[i - 1] == '2')
{
if(i > 1)
dp[i] = dp[i - 1] + dp[i-2];
else
dp[i] = dp[i - 1] + 1;
}
else if(s[i] >'0' && s[i] <= '9' && s[i- 1] == '1')
{
if(i > 1)
dp[i] = dp[i - 1] + dp[i-2];
else
dp[i] = dp[i - 1] + 1;
}
else
{
dp[i] = dp[i - 1];
}
}
return dp[len - 1];
}
};
将字母转换数字来比较:
第i位不为0 dp[i] += dp[i-1] + 1;
第i-1位 a 和第i位 b c = a * 10 + b 10 <= c <= 26 dp[i] += dp[i-2]
代码如下:
class Solution {
public:
int numDecodings(string s) {
int n = s.size();
vector<int> f(n + 1);
f[0] = 1;
for(int i = 1; i <= n; i++)
{
if(s[i - 1] != '0') f[i] = f[i-1];
if(i > 1)
{
int t = (s[i-2] - '0') * 10 + s[i-1] - '0';
if(t >= 10 && t <= 26) f[i] += f[i-2];
}
}
return f[n];
}
};