Decode Ways Algorithm

The Decode Ways Algorithm is a dynamic programming technique used to determine the number of ways a given string of digits can be decoded into a corresponding message, typically using the mapping of integers to their corresponding characters in the alphabet. In this problem, each number between 1 and 26 represents a letter in the alphabet, with 1 being 'A', 2 being 'B', and so on. The algorithm aims to find the total number of possible decodings that can be formed from the given input string, considering all possible combinations of single and double-digit characters. To solve this problem, the algorithm starts by initializing an array or list to store the number of decoding ways for each digit in the input string. The first element of this array is set to 1, as there is only one way to decode the first character. The algorithm then iterates through the input string, updating the array at each position based on the number of ways the current digit and the previous digit can be combined to form a valid character. If the current digit can be combined with the previous digit to form a valid character, the value at the current position in the array is updated by adding the value at the position before the previous digit. If the current digit alone can form a valid character, the value at the current position in the array is updated by adding the value at the previous position. After iterating through the entire input string, the last element in the array represents the total number of decoding ways for the given input.
class Solution {
public:
    int numDecodings(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if (s.empty()) return 0;
        
        vector<int> dp(s.size() + 1, 0);
        dp[0] = 1;
        for (int i = 1; i <= s.size(); i++) {
            if (s[i-1] != '0')
                dp[i] = dp[i-1];
            if (i > 1 && s[i-2] != '0') {
                int x = s[i-2] - '0';
                x = 10 * x + s[i-1] - '0';
                if (0 < x && x <= 26) 
                    dp[i] += dp[i-2];
            }
        }
        return dp[s.size()];
    }
};

LANGUAGE:

DARK MODE: