
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.
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 '.'.