forked from UTSAVS26/PyVerse
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request UTSAVS26#1025 from NK-Works/regular-exp
DP Hard: Regular Expression Matching
- Loading branch information
Showing
2 changed files
with
26 additions
and
0 deletions.
There are no files selected for viewing
24 changes: 24 additions & 0 deletions
24
...ata_Structures/Dynamic-Programming-Series/Hard-DP-Problems/regular-expression-matching.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
def isMatch(s, p): | ||
m, n = len(s), len(p) | ||
|
||
# Initialize a (m+1) x (n+1) DP table | ||
dp = [[False] * (n + 1) for _ in range(m + 1)] | ||
|
||
dp[0][0] = True | ||
|
||
for j in range(1, n + 1): | ||
if p[j - 1] == '*': | ||
dp[0][j] = dp[0][j - 2] | ||
|
||
for i in range(1, m + 1): | ||
for j in range(1, n + 1): | ||
if p[j - 1] == s[i - 1] or p[j - 1] == '.': | ||
dp[i][j] = dp[i - 1][j - 1] | ||
elif p[j - 1] == '*': | ||
dp[i][j] = dp[i][j - 2] or (dp[i - 1][j] and (p[j - 2] == s[i - 1] or p[j - 2] == '.')) | ||
|
||
return dp[m][n] | ||
|
||
s = "aab" | ||
p = "c*a*b" | ||
print(f"Does '{s}' match the pattern '{p}': {isMatch(s, p)}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters