A straightforward solution


  • 0
    Y

    //Could be reduced to O(1) space complexity easily.

    class Solution {
    public:
        int numDecodings(string s) {
            if(s.empty()||s[0]=='0')
                return 0;
            const int s_size = s.size();
            vector<int> dp(s_size,0);
            dp[0]=1;
            for(int i=1; i<s.size(); i++) {
                int v = (s[i-1]-'0')*10 + (s[i]-'0');
                // + dp[i-2] ?
                if( v<=26 && v>=10) dp[i] =  (i>=2? dp[i-2]:1);
                // + dp[i-1] ?
                if(s[i]!='0') dp[i] += dp[i-1];
                if(dp[i]==0)return 0;
            }
            return dp[s_size-1];
        }
    };

Log in to reply
 

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