
Sponsored
Sponsored
This approach uses recursion with memoization to solve the problem efficiently. We recursively compare characters of the input string and the pattern, addressing special characters like '.' and '*'. The memoization is used to store results of sub-problems to avoid redundant calculations, which drastically improves the performance.
Time Complexity: O(m * n), where m and n are the lengths of the string and pattern, respectively. We solve every subproblem once and store the result.
Space Complexity: O(m * n) due to recursion stack and memoization storage.
1#include <vector>
2#include <string>
3using namespace std;
4
5class Solution {
6public:
7 bool isMatch(string s, string p) {
8 vector<vector<int>> memo(s.size() + 1, vector<int>(p.size() + 1, -1));
9 return dfs(0, 0, s, p, memo);
10 }
11 bool dfs(int i, int j, const string& s, const string& p, vector<vector<int>>& memo) {
12 if (memo[i][j] != -1) {
13 return memo[i][j];
14 }
15 if (j == p.size()) {
16 return i == s.size();
17 }
18 bool match = i < s.size() && (s[i] == p[j] || p[j] == '.');
19 if (j + 1 < p.size() && p[j + 1] == '*') {
20 memo[i][j] = dfs(i, j + 2, s, p, memo) || (match && dfs(i + 1, j, s, p, memo));
21 return memo[i][j];
22 }
23 if (match) {
24 memo[i][j] = dfs(i + 1, j + 1, s, p, memo);
25 return memo[i][j];
26 }
27 memo[i][j] = false;
28 return false;
29 }
30};The C++ solution uses a dynamic programming approach through recursive calls, enhanced with a memoization table to track state each (i, j) in the string and pattern. Each recursive call manages the characters and identifies matched conditions or flaws.
This approach involves using a DP table to solve the problem by filling up a boolean matrix iteratively. This avoids recursion and stacks overhead, improving performance in certain scenarios. Each cell in the table represents whether the substring of the pattern matches the substring of the input.
Time Complexity: O(m * n) since we traverse the complete matrix.
Space Complexity: O(m * n) due to the DP table used to store subproblem solutions.
1 public bool IsMatch(string s, string p) {
var dp = new bool[s.Length + 1, p.Length + 1];
dp[0, 0] = true;
for (int j = 1; j < p.Length; j++) {
if (p[j] == '*') {
dp[0, j + 1] = dp[0, j - 1];
}
}
for (int i = 0; i < s.Length; i++) {
for (int j = 0; j < p.Length; j++) {
if (p[j] == '.' || s[i] == p[j]) {
dp[i + 1, j + 1] = dp[i, j];
} else if (p[j] == '*') {
dp[i + 1, j + 1] = dp[i + 1, j - 1] || (dp[i, j + 1] && (p[j - 1] == s[i] || p[j - 1] == '.'));
}
}
}
return dp[s.Length, p.Length];
}
}C# implementation of the DP tabulation augments a matrix to store the relationship between the string and the pattern. By dynamically adjusting the table in successive passes, it uses precedents while addressing symbols '.' and '*' specially.