File tree Expand file tree Collapse file tree 3 files changed +47
-0
lines changed
3-HARD/Python/8-regular-expression-matching-dp/proposed-solution Expand file tree Collapse file tree 3 files changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ # Challenge: Design a regular expression matching engine that supports special characters like '.' and '*',
2+ # using dynamic programming techniques to efficiently handle branching and backtracking.
3+ # Use object-oriented programming and follow the DRY principle.
4+
5+ from regex_matcher import RegexMatcher
6+
7+ def main ():
8+ text = "aab"
9+ pattern = "c*a*b"
10+ matcher = RegexMatcher (text , pattern )
11+ result = matcher .is_match ()
12+ print (f"Text: { text } " )
13+ print (f"Pattern: { pattern } " )
14+ print (f"Match result: { result } " )
15+
16+ if __name__ == "__main__" :
17+ main ()
Original file line number Diff line number Diff line change 1+ class RegexMatcher :
2+ def __init__ (self , text : str , pattern : str ):
3+ self .text = text
4+ self .pattern = pattern
5+ self .dp = [[False ] * (len (pattern ) + 1 ) for _ in range (len (text ) + 1 )]
6+
7+ def is_match (self ) -> bool :
8+ self .dp [0 ][0 ] = True
9+
10+ for j in range (2 , len (self .pattern ) + 1 ):
11+ if self .pattern [j - 1 ] == '*' :
12+ self .dp [0 ][j ] = self .dp [0 ][j - 2 ]
13+
14+ def matches (i , j ):
15+ if self .pattern [j - 1 ] == '.' or self .pattern [j - 1 ] == self .text [i - 1 ]:
16+ return self .dp [i - 1 ][j - 1 ]
17+ if self .pattern [j - 1 ] == '*' :
18+ zero = self .dp [i ][j - 2 ]
19+ one_or_more = (
20+ (self .pattern [j - 2 ] == '.' or self .pattern [j - 2 ] == self .text [i - 1 ])
21+ and self .dp [i - 1 ][j ]
22+ )
23+ return zero or one_or_more
24+ return False
25+
26+ for i in range (1 , len (self .text ) + 1 ):
27+ for j in range (1 , len (self .pattern ) + 1 ):
28+ self .dp [i ][j ] = matches (i , j )
29+
30+ return self .dp [len (self .text )][len (self .pattern )]
You can’t perform that action at this time.
0 commit comments