Leetcode 91. 解码方法

分情况讨论,代码很清楚

class Solution {
public:
    int numDecodings(string s) {
        int pre = 1, now = s[0] == '0' ? 0 : 1;
        for (int i = 1; iif (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;
    }
};

你可能感兴趣的:(Leetcode 91. 解码方法)