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).
解法:注意到字符‘1’,‘2’,‘0’是和其它有些不一样的。在解码的时候会产生不同的结合方式。我们假设n个字符的解码方式又s[n]种,那么在第n+1个字符的时候,我们要考虑前一个是不是特殊字符,来确定最终的解码方式。无非就是s[n-1], s[n-1]+s[n-2],或者直接就是0.
class Solution {
public:
int numDecodings(string s) {
int n = s.size();
if(n == 0) {
return 0;
}
if(s[0] == '0') {
return 0;
}
if(n == 1) {
return 1;
}
vector<int> result(n, 1);
if(s[0] == '1' && s[1] == '0' ||
s[0] == '2' && s[1] == '0') {
result[1] = 1;
}
else if(s[0] == '2' && s[1] <= '6' ||
s[0] == '1') {
result[1] = 2;
}
else if(s[0] > '2' && s[1] == '0') {
return 0;
}
else {
result[1] = 1;
}
for(int i=2; i<n; i++) {
int lastChar = s[i-1];
int currentChar = s[i];
if(currentChar == '0' && (lastChar == '1' || lastChar == '2')) {
result[i] = result[i-2];
}
else if(currentChar == '0') {
return 0;
}
else if(lastChar == '1' ||
lastChar == '2' && currentChar <= '6') {
result[i] = result[i-1] + result[i-2];
}
else {
result[i] = result[i-1];
}
}
return result[n-1];
}
};
值得注意的是,初始值为两个的时候,要把result[1]的值设置清楚,否则后面的结果肯定不对。