
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.
1#include <string>
using namespace std;
class Solution {
public:
bool isMatch(string s, string p) {
vector<vector<bool>> dp(s.size() + 1, vector<bool>(p.size() + 1, false));
dp[0][0] = true;
for (int j = 1; j < p.size(); ++j) {
if (p[j] == '*') {
dp[0][j + 1] = dp[0][j - 1];
}
}
for (int i = 0; i < s.size(); ++i) {
for (int j = 0; j < p.size(); ++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] && (s[i] == p[j - 1] || p[j - 1] == '.'));
}
}
}
return dp[s.size()][p.size()];
}
};This C++ solution leverages tabulation with a matrix employed to store states of string-pattern matches. It iteratively adjusts the table based on character conditions, managing '.' and '*' in the pattern for successful or unmatched cases.