File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
problems/dynamic_programming
tests/dynamic_programming Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ class RegularExpressionMatching :
2+ @staticmethod
3+ def isMatch (s : str , p : str ) -> bool :
4+ # Lengths of strings
5+ m , n = len (s ), len (p )
6+ # Lookup table to store if s[0...i] matches with p[0...j]
7+ lookup = [[False ] * (n + 1 ) for _ in range (m + 1 )]
8+ # Empty string matches with empty pattern
9+ lookup [0 ][0 ] = True
10+ # For empty string and star pattern
11+ for j in range (2 , n + 1 ):
12+ if p [j - 1 ] == '*' :
13+ lookup [0 ][j ] = lookup [0 ][j - 2 ]
14+ # Populate the remaining table
15+ for i in range (1 , m + 1 ):
16+ for j in range (1 , n + 1 ):
17+ # If characters are same or we have period in pattern
18+ if s [i - 1 ] == p [j - 1 ] or p [j - 1 ] == '.' :
19+ lookup [i ][j ] = lookup [i - 1 ][j - 1 ]
20+ elif j > 1 and p [j - 1 ] == '*' :
21+ lookup [i ][j ] = lookup [i ][j - 2 ]
22+ if p [j - 2 ] == '.' or s [i - 1 ] == p [j - 2 ]:
23+ lookup [i ][j ] = lookup [i ][j ] | lookup [i - 1 ][j ]
24+ return lookup [m ][n ]
Original file line number Diff line number Diff line change 1+ import unittest
2+
3+ from problems .dynamic_programming .regular_expression_matching import RegularExpressionMatching
4+
5+
6+ class TestRegularExpressionMatching (unittest .TestCase ):
7+
8+ def setUp (self ):
9+ self .regular_expression_matching = RegularExpressionMatching ()
10+
11+ def test_is_match (self ):
12+ self .assertTrue (self .regular_expression_matching .isMatch ("aa" , "a*" ))
13+ self .assertTrue (self .regular_expression_matching .isMatch ("ab" , ".*" ))
14+ self .assertFalse (self .regular_expression_matching .isMatch ("mississippi" , "mis*is*p*." ))
15+ self .assertTrue (self .regular_expression_matching .isMatch ("aab" , "c*a*b" ))
16+ self .assertFalse (self .regular_expression_matching .isMatch ("ab" , "a" ))
17+ self .assertTrue (self .regular_expression_matching .isMatch ("" , ".*" ))
18+ self .assertTrue (self .regular_expression_matching .isMatch ("" , "a*" ))
19+ self .assertFalse (self .regular_expression_matching .isMatch ("abcd" , "d*" ))
20+ self .assertTrue (self .regular_expression_matching .isMatch ("aaa" , "a*a" ))
21+ self .assertFalse (self .regular_expression_matching .isMatch ("aaa" , "ab*a" ))
22+
23+
24+ if __name__ == "__main__" :
25+ unittest .main ()
You can’t perform that action at this time.
0 commit comments