|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Function to determine if the string matches the pattern using space-optimized dynamic programming |
| 4 | + int solve(string &str, string &ptrn) { |
| 5 | + int n = str.length(); // Length of the input string |
| 6 | + int m = ptrn.length(); // Length of the pattern |
| 7 | + |
| 8 | + // Two 1D vectors for storing the current and previous rows of the DP table |
| 9 | + vector<int> prev(m + 1, 0); // Represents the DP state for the previous row |
| 10 | + vector<int> curr(m + 1, 0); // Represents the DP state for the current row |
| 11 | + |
| 12 | + // Base case: An empty string matches an empty pattern |
| 13 | + prev[0] = true; |
| 14 | + |
| 15 | + // Handle cases where the string is empty but the pattern has characters |
| 16 | + for (int j = 1; j <= m; j++) { |
| 17 | + bool flag = true; // Check if all characters in the pattern up to `j` are '*' |
| 18 | + for (int k = 1; k <= j; k++) { |
| 19 | + if (ptrn[k - 1] != '*') { // If a non-'*' character is found, stop |
| 20 | + flag = false; |
| 21 | + break; |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + // Set `prev[j]` to true if all characters in the pattern are '*', otherwise false |
| 26 | + prev[j] = flag; |
| 27 | + } |
| 28 | + |
| 29 | + // Iterate over the characters in the string |
| 30 | + for (int i = 1; i <= n; i++) { |
| 31 | + // Iterate over the characters in the pattern |
| 32 | + for (int j = 1; j <= m; j++) { |
| 33 | + // Case 1: Characters match or the pattern has '?' |
| 34 | + if (str[i - 1] == ptrn[j - 1] || ptrn[j - 1] == '?') { |
| 35 | + curr[j] = prev[j - 1]; // Match depends on the previous diagonal value |
| 36 | + } |
| 37 | + // Case 2: Pattern has '*' |
| 38 | + // '*' can match the current character (`prev[j]`) or match zero characters (`curr[j-1]`) |
| 39 | + else if (ptrn[j - 1] == '*') { |
| 40 | + curr[j] = prev[j] || curr[j - 1]; |
| 41 | + } |
| 42 | + // Case 3: Characters do not match and there's no wildcard |
| 43 | + else { |
| 44 | + curr[j] = false; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // After processing the current row, update `prev` to be the same as `curr` |
| 49 | + prev = curr; |
| 50 | + } |
| 51 | + |
| 52 | + // The result for the full string and pattern is stored in `prev[m]` |
| 53 | + return prev[m]; |
| 54 | + } |
| 55 | + |
| 56 | + // Main function to check if the string matches the pattern |
| 57 | + bool isMatch(string s, string p) { |
| 58 | + return solve(s, p); |
| 59 | + } |
| 60 | +}; |
0 commit comments