|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive function to check if the pattern matches the string |
| 4 | + int solve(string &str, string &ptrn, int i, int j) { |
| 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 only the pattern is exhausted but the string is not, return false |
| 9 | + if (j < 0) return false; |
| 10 | + |
| 11 | + // Base case: If only the 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 | + // Case 1: If characters match or the pattern has a '?', move both pointers |
| 21 | + if (str[i] == ptrn[j] || ptrn[j] == '?') { |
| 22 | + return solve(str, ptrn, i - 1, j - 1); |
| 23 | + } |
| 24 | + // Case 2: If the pattern has a '*', there are two possibilities: |
| 25 | + // - Treat '*' as matching the current character in the string (move string pointer `i` only) |
| 26 | + // - Treat '*' as matching zero characters (move pattern pointer `j` only) |
| 27 | + else if (ptrn[j] == '*') { |
| 28 | + return solve(str, ptrn, i - 1, j) || solve(str, ptrn, i, j - 1); |
| 29 | + } |
| 30 | + // Case 3: If characters don't match and it's not a wildcard, return false |
| 31 | + else { |
| 32 | + return false; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + // Main function to check if the string matches the pattern |
| 37 | + bool isMatch(string s, string p) { |
| 38 | + // Start the recursive process from the last characters of both string and pattern |
| 39 | + return solve(s, p, s.length() - 1, p.length() - 1); |
| 40 | + } |
| 41 | +}; |
0 commit comments