A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26Given 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.
分析:该题与Climbing Stairs 类似,只是多了几条判断语句。
// LeetCode, Decode Ways
// 动态规划,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int numDecodings(const string s) {
if (s.empty() || s[0] == '0') return 0;
int prev = 0;
int cur = 1;
// 长度为n的字符串,有n+1个阶梯
for (size_t i = 1; i <= s.size(); ++i) {
if (s[i-1] == '0') cur = 0;
if (i < 2 || !(s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6')))
//当i < 2 或者 i 超过 1~26 的范围,将重置prev.
prev = 0;
int tmp = cur;
cur = prev + cur;
prev = tmp;
}
return cur;
}
};
本文介绍了一种基于动态规划的解码方式计数算法,用于计算字母编码为数字后的解码可能性总数。通过示例解释了算法原理,并提供了一个高效的时间复杂度为O(n)的实现方案。

被折叠的 条评论
为什么被折叠?



