DSA - Decode Ways - C++,Dynamic Programming

Hey, so today we are going to solve Leetcode - Decode Ways

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

class Solution {
public:

     int numDecodings(string s) {
     if(s.length() == 0 || s[0] = '0'){
      return 0;
     }

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

     for(int i=2; i<=s.length(); i++){
     int oneDig = stoi(s.substr(i-1, 1));
     int twoDig = stoi(s.substr(i-2, 2)); 

     if(oneDig >= 1 && oneDig <= 9) {
     dp[i] += dp[i-1];
     }

     if(twoDig >= 10 && twoDig <= 26) {
     dp[i] += dp[i-2];
     }
     }

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

The numDecodings function takes a string s as input and returns the number of ways to decode the string. The function first checks if the input string is empty or if it starts with a 0, in which case there are no valid decodings and the function returns 0.

The function then initializes a dynamic programming array dp of length n + 1, where dp[i] represents the number of ways to decode the substring s[0:i-1].

The base case is dp[0] = 1, since there is only one way to decode an empty string, and dp[1] = 1 if the first digit is not 0, since there is only one way to decode a single-digit string.

The function then loops through the remaining substrings of s and computes dp[i] based on the previous values in the dp array. Specifically, for each substring s[0:i-1], the function considers two cases:

  • The last digit s[i-1] can be decoded as a single digit. In this case, the number of decodings is the same as the number of decodings of the substring s[0:i-2], which is stored in dp[i-1].

  • The last two digits s[i-2:i-1] can be decoded as a two-digit number. In this case, the number of decodings is the same as the number of decodings of the substring s[0:i-3], which is stored in dp[i-2].

The function returns dp[n], which represents the number of ways to decode the entire input string s.