
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.
1using System;
2public class Solution {
3 public bool IsMatch(string s, string p) {
4 int sLen = s.Length, pLen = p.Length;
5 bool?[,] memo = new bool?[sLen + 1, pLen + 1];
6 return dfs(0, 0, s, p, memo);
7 }
8 private bool dfs(int i, int j, string s, string p, bool?[,] memo) {
9 if (memo[i, j] != null) {
10 return memo[i, j].Value;
11 }
12 if (j == p.Length) {
13 return i == s.Length;
14 }
15 bool match = i < s.Length && (s[i] == p[j] || p[j] == '.');
16 if (j + 1 < p.Length && p[j + 1] == '*') {
17 memo[i, j] = dfs(i, j + 2, s, p, memo) || (match && dfs(i + 1, j, s, p, memo));
18 return memo[i, j].Value;
19 }
20 if (match) {
21 memo[i, j] = dfs(i + 1, j + 1, s, p, memo);
22 return memo[i, j].Value;
23 }
24 memo[i, j] = false;
25 return false;
26 }
27}C# implementation uses a 2D nullable boolean array to store results of computed states, ensuring efficient recursion handling. Identifying '.' and '*' within pattern, the dfs method customizes the string conformity to regex constraints.
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.
1The JavaScript variant leverages dynamic programming with tabulation to manage the comparison of string and pattern substrings. The 2D array signifies configurations of aligned sections, structured to accommodate regex attributes of '.' and '*' through condition logic.