Problem Description
Given an input string s and a pattern p, implement regular expression matching with support for '.' (matches any single character) and '*' (matches zero or more of the preceding element). The matching should cover the entire input string.
Key Insights
- Use recursion or dynamic programming to simulate matching as the '*' operator can affect the current and following characters.
- The '.' operator is a wildcard that matches any single character.
- When encountering a '*' in the pattern, consider both skipping the preceding element or consuming one character from the string if it matches.
- Using memoization helps to save intermediate results and efficiently process overlapping subproblems.
Space and Time Complexity
Time Complexity: O(mn) where m = length(s) and n = length(p), due to exploring each subproblem combination. Space Complexity: O(mn) for storing the memoization table in the dynamic programming or recursive approach.
Solution
The solution uses a top-down recursive strategy with memoization to efficiently match the string against the pattern. For each character position in s and p, we check if they match directly or if the pattern character is '.' to allow any match. When encountering '' in the pattern, two possibilities are explored: either the '' stands for zero occurrences of the preceding element, or if there is a valid match, it accounts for one occurrence and we proceed further in the string while maintaining the same pattern index. The memoization aspect prevents repeated computations of the same (i, j) state in the recursion, resulting in an improved overall runtime.