
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.
1function isMatch(s, p) {
2 const memo = Array.from({ length: s.length + 1 }, () => Array(p.length + 1).fill(undefined));
3 function dfs(i, j) {
4 if (memo[i][j] !== undefined) {
5 return memo[i][j];
6 }
7 if (j === p.length) {
8 return i === s.length;
9 }
10 const match = i < s.length && (s[i] === p[j] || p[j] === '.');
11 if ((j + 1) < p.length && p[j + 1] === '*') {
12 memo[i][j] = dfs(i, j + 2) || (match && dfs(i + 1, j));
13 return memo[i][j];
14 }
15 if (match) {
16 memo[i][j] = dfs(i + 1, j + 1);
17 return memo[i][j];
18 }
19 memo[i][j] = false;
20 return false;
21 }
22 return dfs(0, 0);
23}The JavaScript solution uses a 2D array to memorize results of subproblems within the recursive process. This allows bypassing recalculations and adjusting decisions based on the appearance of special regex characters in the pattern.
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.