Leetcode 91 Solution

This article provides solution to leetcode question 91 (decode-ways)

https://leetcode.com/problems/decode-ways

Solution

class Solution {
public:
    int numDecodings(string s) {
        if (s.size() == 0)
            return 0;

        vector<int> dp(s.size() + 1);
        dp[0] = 1;

        for (int i = 1; i <= s.size(); i++)
        {
            if ('1' <= s[i - 1] && s[i - 1] <= '9')
                dp[i] += dp[i - 1];

            if (i > 1
                && '1' <= s[i - 2] && s[i - 2] <= '9'
                && '0' <= s[i - 1] && s[i - 1] <= '9')
            {
                int val = (s[i - 2] - '0') * 10 + s[i - 1] - '0';

                if (1 <= val && val <= 26)
                    dp[i] += dp[i - 2];
            }

        }
        return dp[s.size()];
    }
};