-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add regex matching implementation in C and Python
- Loading branch information
Showing
2 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
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,31 @@ | ||
// 10. Regex Matching | ||
|
||
#include <stdbool.h> | ||
#include <stdio.h> | ||
|
||
bool isMatch(char *s, char *p) | ||
{ | ||
if (*p == '\0') | ||
{ | ||
return *s == '\0'; | ||
} | ||
|
||
bool firstMatch = *s && (*s == *p || *p == '.'); | ||
|
||
if (*(p + 1) == '*') | ||
{ | ||
return isMatch(s, p + 2) || (firstMatch && isMatch(s + 1, p)); | ||
} | ||
else | ||
{ | ||
return firstMatch && isMatch(s + 1, p + 1); | ||
} | ||
} | ||
|
||
int main() | ||
{ | ||
char s[] = "aaaaaaa"; | ||
char p[] = "a*"; | ||
printf("%d\n", isMatch(s, p)); | ||
return 0; | ||
} |
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,22 @@ | ||
# 10. Regex Matching | ||
|
||
from __future__ import annotations | ||
|
||
import itertools | ||
|
||
|
||
class Solution: | ||
def isMatch(self, s: str, p: str) -> bool: | ||
dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)] | ||
dp[-1][-1] = True | ||
|
||
for i, j in itertools.product(range(len(s), -1, -1), range(len(p) - 1, -1, -1)): | ||
first_match = i < len(s) and p[j] in {s[i], "."} | ||
dp[i][j] = dp[i][j + 2] or first_match and dp[i + 1][j] if j + 1 < len(p) and p[j + 1] == "*" else first_match and dp[i + 1][j + 1] | ||
return dp[0][0] | ||
|
||
|
||
if __name__ == "__main__": | ||
sol = Solution() | ||
print(sol.isMatch("aa", "a")) # False | ||
print(sol.isMatch("aa", "a*")) # True |