Skip to content

Commit

Permalink
feat: Add regex matching implementation in C and Python
Browse files Browse the repository at this point in the history
  • Loading branch information
rtk-rnjn committed Jul 7, 2024
1 parent 6a61707 commit 4bb31ba
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
31 changes: 31 additions & 0 deletions CP/LeetCode/C/10.c
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;
}
22 changes: 22 additions & 0 deletions CP/LeetCode/Python/10.py
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

0 comments on commit 4bb31ba

Please sign in to comment.