
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.
1def isMatch(s, p):
2 memo = {}
3 def dfs(i, j):
4 if (i, j) in memo:
5 return memo[(i, j)]
6 if j == len(p):
7 return i == len(s)
8 match = i < len(s) and (s[i] == p[j] or p[j] == '.')
9 if (j + 1) < len(p) and p[j+1] == '*':
10 memo[(i, j)] = dfs(i, j + 2) or (match and dfs(i + 1, j))
11 return memo[(i, j)]
12 if match:
13 memo[(i, j)] = dfs(i + 1, j + 1)
14 return memo[(i, j)]
15 memo[(i, j)] = False
16 return False
17 return dfs(0, 0)The Python solution uses a depth-first search (DFS) approach with memoization to tackle overlapping subproblems. We check if characters at position i in the string and j in the pattern match directly or through special symbols. The '*' in the pattern is handled by either skipping it or considering it as multiple matches.
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 Python DP solution constructs a 2D boolean array where dp[i][j] signifies if the first i characters of the string match the first j characters of the pattern. The matrix is initialized with the base conditions and filled based on the characters in pattern string, iteratively updating for mismatches dictated by '*' or '.'.