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.
//下述算法应该是对的,不过超时
// class Solution
// {
// public:
// int numDecodings(string s)
// {
// if (s.length() == 0)
// {
// return 0;
// }
// else if (s.length() == 1)
// {
// if (s == "0")
// {
// return 0;
// }
// return 1;
// }
// else if (s.length() == 2)
// {
// int temp = atoi(s.c_str());
// if (temp < 10)
// {
// return 0;
// }
// if ((temp == 10) || (temp == 20))
// {
// return 1;
// }
// if(temp > 26)
// {
// if (temp %10 == 0)
// {
// return 0;
// }
// else
// {
// return 1;
// }
// }
// return 2;
// }
// else if (s.length() >= 3)
// {
// string sub = s.substr(0,2);
// string sub_later = s.substr(2);
// return numDecodings(s.substr(0,1))*numDecodings(s.substr(1)) + numDecodings(s.substr(0,2))*numDecodings(s.substr(2));
// }
// }
// };
//
//正确解法
class Solution {
public:
int numDecodings(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s.empty()) {
return 0;
}
int length = s.length();
int *f = new int[length]/*f[length]*/;
memset(f, 0, sizeof(int) * length);
for (int i = 0; i < length; i++) {
if (s[i] < '0' || s[i] > '9') {
return 0;
}
else if (s[i] == '0') {
if (i == 0 || s[i - 1] == '0' || s[i - 1] > '2') {
return 0;
}
else {
f[i] = i > 1 ? f[i - 2] : 1;
}
}
else {
if (i > 0 && (s[i - 1] == '1' || s[i - 1] == '2' && s[i] <= '6')) {
f[i] = (i > 0 ? f[i - 1] : 1) + (i > 1 ? f[i - 2] : 1);
}
else {
f[i] = i > 0 ? f[i - 1] : 1;
}
}
}
return f[length - 1];
}
};