Sponsored
Sponsored
The dynamic programming approach uses a 2D table to store results of subproblems. We define dp[i][j] as True if the first i characters in the string s can be matched by the first j characters of the pattern p.
Base Cases:
Fill the table using the following rules:
Time Complexity: O(m*n) where m and n are the lengths of s and p, respectively.
Space Complexity: O(m*n) due to the storage of the dp table.
1#include <stdbool.h>
2#include <string.h>
3
4bool isMatch(char * s, char * p) {
5 int m The code initializes a boolean matrix dp such that dp[i][j] is True if the first i characters of s match with the first j characters of p.
We handle '*' using two cases: either it matches the empty sequence, so we look to the left; or it matches one or more characters, so we look above.
The greedy algorithm approach tracks the position of the last '*' in the pattern and attempts to match remaining characters greedily. We maintain two pointers, one for the string and one for the pattern. When encountering '*', we remember the positions of both pointers in order to backtrack if needed.
If characters in p and s match or if the pattern has '?', both pointers are incremented. For '*', we shift the pattern pointer and remember indices for future potential matches. If there's a mismatch after '*', we use these remembered indices to backtrack.
Time Complexity: O(m + n) due to possible backtracking
Space Complexity: O(1) requiring constant storage for indices.
public bool IsMatch(string s, string p) {
int sLen = s.Length;
int pLen = p.Length;
int sIdx = 0, pIdx = 0;
int starIdx = -1, sTmpIdx = -1;
while (sIdx < sLen) {
if (pIdx < pLen && (p[pIdx] == '?' || s[sIdx] == p[pIdx])) {
sIdx++;
pIdx++;
} else if (pIdx < pLen && p[pIdx] == '*') {
starIdx = pIdx;
sTmpIdx = sIdx;
pIdx++;
} else if (starIdx == -1) {
return false;
} else {
pIdx = starIdx + 1;
sTmpIdx++;
sIdx = sTmpIdx;
}
}
for (int i = pIdx; i < pLen; i++) {
if (p[i] != '*') {
return false;
}
}
return true;
}
}
Pursuing the same logic framework, the C# version aligns currently observed characters, applying star pattern memory for context shifts when needed.