10 lines, O(N) Time and O(1) Space , C++ Solution


  • 0
    L
    class Solution {
    public:
        int numDecodings(string s) {
            int len = s.length();
            if(len == 0)return 0;
            int a = s[len-1] == '0' ? 0 : 1, b = 1;
            for(int i = len-2; i >= 0; i--){
                int c = b;
                b = a;
                if(s[i] == '0')a = 0;
                else a = atoi(s.substr(i, 2).c_str()) <= 26 ? b+c : b;
            }
            return a;
        }
    };

Log in to reply
 

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