Easy-to-Understand C++ Solution


  • 0
    class Solution {
    public:
        int numDecodings(string s) {
            if (!s.size()) return 0;
            int prev = s[s.size() - 1] == '0' ? 0 : 1, prev_prev = 1, cur = 0;
            for (int j = s.size() - 2; j >= 0; j--) {
                if (s[j] == '0')
                    cur = 0;
                else {
                    cur = prev;
                    if (stoi(s.substr(j, 2)) <= 26) cur += prev_prev;
                }
                prev_prev = prev;
                prev = cur;
            }
            return prev;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.