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;
}
};