|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive function to check if the pattern matches the string with memoization |
| 4 | + int solve(string &str, string &ptrn, int i, int j, vector<vector<int>> &dp) { |
| 5 | + // Base case: If both string and pattern are exhausted, return true |
| 6 | + if (i < 0 && j < 0) return true; |
| 7 | + |
| 8 | + // Base case: If pattern is exhausted but the string is not, return false |
| 9 | + if (j < 0) return false; |
| 10 | + |
| 11 | + // Base case: If string is exhausted |
| 12 | + if (i < 0) { |
| 13 | + // Check if the remaining characters in the pattern are all '*' |
| 14 | + for (int k = 0; k <= j; k++) { |
| 15 | + if (ptrn[k] != '*') return false; |
| 16 | + } |
| 17 | + return true; |
| 18 | + } |
| 19 | + |
| 20 | + // Check if the result for this state is already computed |
| 21 | + if (dp[i][j] != -1) return dp[i][j]; |
| 22 | + |
| 23 | + // Case 1: If characters match or the pattern has '?', move both pointers |
| 24 | + if (str[i] == ptrn[j] || ptrn[j] == '?') { |
| 25 | + dp[i][j] = solve(str, ptrn, i - 1, j - 1, dp); |
| 26 | + } |
| 27 | + // Case 2: If the pattern has '*', there are two possibilities: |
| 28 | + // - Treat '*' as matching the current character (move string pointer `i` only) |
| 29 | + // - Treat '*' as matching zero characters (move pattern pointer `j` only) |
| 30 | + else if (ptrn[j] == '*') { |
| 31 | + dp[i][j] = solve(str, ptrn, i - 1, j, dp) || solve(str, ptrn, i, j - 1, dp); |
| 32 | + } |
| 33 | + // Case 3: If characters don't match and it's not a wildcard, return false |
| 34 | + else { |
| 35 | + dp[i][j] = false; |
| 36 | + } |
| 37 | + |
| 38 | + // Return the computed result for this state |
| 39 | + return dp[i][j]; |
| 40 | + } |
| 41 | + |
| 42 | + // Main function to check if the string matches the pattern |
| 43 | + bool isMatch(string s, string p) { |
| 44 | + int n = s.length(); // Length of the string |
| 45 | + int m = p.length(); // Length of the pattern |
| 46 | + |
| 47 | + // Initialize a 2D DP array with -1, where dp[i][j] represents the result |
| 48 | + // of matching the first i characters of the string with the first j characters of the pattern |
| 49 | + vector<vector<int>> dp(n + 1, vector<int>(m + 1, -1)); |
| 50 | + |
| 51 | + // Start the recursive process with memoization |
| 52 | + return solve(s, p, n - 1, m - 1, dp); |
| 53 | + } |
| 54 | +}; |
0 commit comments