|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Function to determine if the string matches the pattern using dynamic programming |
| 4 | + int solve(string &str, string &ptrn) { |
| 5 | + int n = str.length(); // Length of the string |
| 6 | + int m = ptrn.length(); // Length of the pattern |
| 7 | + |
| 8 | + // DP table to store the results of subproblems |
| 9 | + // dp[i][j] represents whether the first `i` characters of the string match the first `j` characters of the pattern |
| 10 | + vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0)); |
| 11 | + |
| 12 | + // Base case: An empty string matches an empty pattern |
| 13 | + dp[0][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 | + dp[0][j] = flag; // Set `dp[0][j]` to true if all characters are '*', otherwise false |
| 25 | + } |
| 26 | + |
| 27 | + // Fill the DP table for cases where both string and pattern have characters |
| 28 | + for (int i = 1; i <= n; i++) { // Iterate over the string |
| 29 | + for (int j = 1; j <= m; j++) { // Iterate over the pattern |
| 30 | + // Case 1: Characters match or the pattern has '?' |
| 31 | + if (str[i - 1] == ptrn[j - 1] || ptrn[j - 1] == '?') { |
| 32 | + dp[i][j] = dp[i - 1][j - 1]; |
| 33 | + } |
| 34 | + // Case 2: Pattern has '*' |
| 35 | + // - '*' can match the current character in the string (move string pointer `i-1`) |
| 36 | + // - '*' can match zero characters (move pattern pointer `j-1`) |
| 37 | + else if (ptrn[j - 1] == '*') { |
| 38 | + dp[i][j] = dp[i - 1][j] || dp[i][j - 1]; |
| 39 | + } |
| 40 | + // Case 3: Characters do not match and there's no wildcard |
| 41 | + else { |
| 42 | + dp[i][j] = false; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // The result for the full string and pattern is stored in `dp[n][m]` |
| 48 | + return dp[n][m]; |
| 49 | + } |
| 50 | + |
| 51 | + // Main function to check if the string matches the pattern |
| 52 | + bool isMatch(string s, string p) { |
| 53 | + return solve(s, p); |
| 54 | + } |
| 55 | +}; |
0 commit comments