Skip to content

Commit 6e2eea7

Browse files
committed
"Regular Expression Matching" solution
1 parent 9427ba1 commit 6e2eea7

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/regular_expression_matching.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def isMatch(self, s: str, p: str) -> bool:
3+
cache: dict[tuple[int, int], bool] = {}
4+
5+
def dfs(i: int, j: int) -> bool:
6+
if (i, j) in cache:
7+
return cache[(i, j)]
8+
9+
if i >= len(s) and j >= len(p):
10+
result = True
11+
elif i >= len(s) and j < len(p) - 1 and p[j + 1] == "*":
12+
result = dfs(i, j + 2)
13+
elif i == len(s) or j == len(p):
14+
result = False
15+
elif j < len(p) - 1 and p[j + 1] == "*":
16+
if s[i] == p[j] or p[j] == ".":
17+
result = dfs(i + 1, j) or dfs(i, j + 2)
18+
else:
19+
result = dfs(i, j + 2)
20+
elif p[j] == ".":
21+
result = dfs(i + 1, j + 1)
22+
elif s[i] != p[j]:
23+
result = False
24+
else:
25+
result = dfs(i + 1, j + 1)
26+
27+
cache[(i, j)] = result
28+
return result
29+
30+
return dfs(0, 0)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import pytest
2+
3+
from src.regular_expression_matching import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
"s,p,expected",
8+
(
9+
("aa", "a", False),
10+
("aa", "a*", True),
11+
("ab", ".*", True),
12+
("a", "a*b*", True),
13+
("aabcbcbcaccbcaabc", ".*a*aa*.*b*.c*.*a*", True),
14+
),
15+
)
16+
def test_solution(s, p, expected):
17+
assert Solution().isMatch(s, p) is expected

0 commit comments

Comments
 (0)