091. Decode Ways
Difficulty: Medium
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.
思路
类似斐波那契数列,以“12304”的解码为例,用以下表达式表示解码可得到的不同结果数:
f(“12304”) = f(“1230”)g(“4”) + f(“123”)g(“04”);
f(“1230”) = f(“123”)g(“0”) + f(“12”)g(“30”)。
g(s)判断s是否可以解码得到单个字母,返回结果只有1和0,如g(“1”)=1,g(“27”)=0。
此外需要注意“0”和“04”都不可解码,即只要‘0’为字符串的第一个字符,该字符串不可解码,g(“0.*”) = 0。
用循环比递归更高效,减少重复运算。
代码
[C++]
class Solution {
public:
int numDecodings(string s) {
if (s.size() <= 0)
return 0;
int numOne, numTwo;
numOne = numTwo = 1;
int Final = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '0')
numTwo = 0;
Final = numTwo;
if (IsEncoded(s, i))
Final += numOne;
numOne = numTwo;
numTwo = Final;
}
return Final;
}
bool IsEncoded(const string &s, int index) {
if (index < s.size() && index > 0) {
string temp(s, index - 1, 2);
int num = stoi(temp, NULL);
if (num > 9 && num <= 26)
return true;
}
return false;
}
};
本文介绍了一种中等难度的算法题——解码方式计数。消息中的字母被编码成1到26的数字,文章详细解释了如何计算一个数字串能解码成的不同字母组合的数量,并给出了高效的循环实现而非递归。
430

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



