Easy DP solution C++


  • 0
    C
    class Solution {
    public:
        int numDecodings(string s) {
            if(s.length()==0) return 0;
            if(s.length()==1) return s[0]=='0'?0:1;
            
            vector<int>dp(s.length()+1,0);
            dp[0] = 1;
            dp[1] = (s[0]=='0')?0:1;
            for(int i = 2; i<s.length()+1; i++)
            {
                if(s[i-1]!='0') dp[i] += dp[i-1];
                if(stoi(s.substr(i-2,2))<=26 && s[i-2]!='0') dp[i] += dp[i-2];
            }
            return dp[s.length()];
        }
    };

  • 0
    C
    This post is deleted!

Log in to reply
 

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