Skip to content

Commit

Permalink
Merge pull request UTSAVS26#1025 from NK-Works/regular-exp
Browse files Browse the repository at this point in the history
DP Hard: Regular Expression Matching
  • Loading branch information
UTSAVS26 authored Nov 3, 2024
2 parents 25ede8a + 793a44b commit b1a80e0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
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)}")
2 changes: 2 additions & 0 deletions Project-Structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@
* [Climbing-Stairs](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Basic-DP-Problems/climbing-stairs.py)
* [Fibonacci-Seq](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Basic-DP-Problems/fibonacci-seq.py)
* [House-Robber](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Basic-DP-Problems/house-robber.py)
* Hard-Dp-Problems
* [Regular-Expression-Matching](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Hard-DP-Problems/regular-expression-matching.py)
* Medium-Dp-Problems
* [Coin-Change](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/coin-change.py)
* [Longest-Inc-Subseq](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/longest-inc-subseq.py)
Expand Down

0 comments on commit b1a80e0

Please sign in to comment.