分情况讨论,代码很清楚
class Solution {
public:
int numDecodings(string s) {
int pre = 1, now = s[0] == '0' ? 0 : 1;
for (int i = 1; i<s.size(); ++i) {
if (s[i] == '0') {
if (s[i - 1] != '1' &&s[i - 1] != '2') return 0;
else swap(pre, now);
}
else {
if (string(s, i - 1, 2) <= "26" && s[i - 1] != '0') now += pre, pre = now - pre;
else pre = now;
}
}
return now;
}
};