11class Solution :
22 """Base class for all LeetCode Problems."""
33
4- def isMatch (self , s : str , p : str ) -> bool :
4+ def isMatchTD (self , s : str , p : str ) -> bool :
55 """
66 Given an input string s and a pattern p, implement regular expression matching
77 with support for '.' and '*' where:
@@ -10,6 +10,7 @@ def isMatch(self, s: str, p: str) -> bool:
1010
1111 The matching should cover the entire input string (not partial).
1212 """
13+ # Top-Down Dynamic Programming (Memoization)
1314 # Time Complexity: O(n²)
1415 # Space Complexity: O(n²)
1516 dp = {}
@@ -32,3 +33,34 @@ def dfs(i: int, j: int) -> bool:
3233 return False
3334
3435 return dfs (0 , 0 )
36+
37+ def isMatchBU (self , s : str , p : str ) -> bool :
38+ """
39+ Given an input string s and a pattern p, implement regular expression matching
40+ with support for '.' and '*' where:
41+ - '.' Matches any single characters.
42+ - '*' Matches zero or more of the preceding element.
43+
44+ The matching should cover the entire input string (not partial).
45+ """
46+ # Bottom-Up Dynamic Programming (Tabulation)
47+ # Time Complexity: O(n²)
48+ # Space Complexity: O(n²)
49+ dp = [[False for _ in range (len (p ) + 1 )] for _ in range (len (s ) + 1 )]
50+ dp [0 ][0 ] = True
51+
52+ # Initialize first row
53+ for j in range (1 , len (p ) + 1 ):
54+ if p [j - 1 ] == "*" :
55+ dp [0 ][j ] = dp [0 ][j - 2 ]
56+
57+ # Fill the DP table
58+ for i in range (1 , len (s ) + 1 ):
59+ for j in range (1 , len (p ) + 1 ):
60+ if p [j - 1 ] == "." or p [j - 1 ] == s [i - 1 ]:
61+ dp [i ][j ] = dp [i - 1 ][j - 1 ]
62+ elif p [j - 1 ] == "*" :
63+ dp [i ][j ] = dp [i ][j - 2 ]
64+ if p [j - 2 ] == "." or p [j - 2 ] == s [i - 1 ]:
65+ dp [i ][j ] = dp [i ][j ] or dp [i - 1 ][j ]
66+ return dp [- 1 ][- 1 ]
0 commit comments