The user wants a program that implements a regular expression matching algorithm.
I need to decide:
Which language? Python is a good choice for readability and conciseness, but C++ or Java show the underlying logic better. I'll stick with Python as it's widely understood, but I'll implement the logic from scratch (dynamic programming or recursion) rather than just calling re.match. Actually, to be thorough, I should probably provide an implementation that handles specific common regex tokens (like . and *) to demonstrate the algorithm, rather than building a full regex engine. The prompt asks for "the" algorithm, which usually implies the classic LeetCode/interview style problem ("Matching with '.' and '*'").
Scope of the Regex: A full regex engine (NFA/DFA construction) is too complex for a single code snippet without a library. The most common interpretation of this request in a programming context is the classic "Regular Expression Matching" problem (often found on LeetCode or in CLRS). This usually involves:
. matches any single character.
* matches zero or more of the preceding element.
Exact character matches.
Algorithm Approach:
Recursion (Backtracking): Intuitive but potentially slow (exponential) without memoization.
Dynamic Programming (Top-down with Memoization): Efficient and elegant.
Dynamic Programming (Bottom-up): Efficient and standard.
Structure of the Response:
Explanation of the problem scope (matching . and *).
Recursive solution (for intuition).
Dynamic Programming solution (for efficiency).
Code examples in a popular language (Python is best here).
Let's refine the Python implementation.
Input: String s, Pattern p.
Base cases:
If p is empty: return s is empty.
First match check: bool(s) and p[0] matches s[0] (either equal or .).
Handling *:
If length of p >= 2 and p[1] == '*':
Case 1: Treat x* as empty (skip 2 chars in p). Recursive call: match(s, p[2:]).
Case 2: Use x* to match char (if first match). Recursive call: match(s[1:], p).
Else (no star):
Must have first match. Recursive call: match(s[1:], p[1:]).
This is the "Top-Down" approach. I will add memoization to make it DP.
Alternative interpretation: The user might want a library implementation. But "implement the algorithm" implies writing the logic, not using a library.
Let's write the code.
Plan:
Define the problem: Implement regex matching supporting . and *.
Provide a clean, commented Python class/function.
Use Dynamic Programming (Top-Down) because it's readable and efficient.
Explain how it works.
(Optional) Mention that real-world regex engines use NFAs/DFAs (Thompson's construction), but the recursive/DP approach is the standard algorithmic solution for the matching subset problem. I'll stick to the DP solution as it's the most practical answer to "write a program that implements...".
Drafting the Code:
python
def isMatch(s: str, p: str) -> bool:
memo = {}
def dp(i, j):
if (i, j) in memo: return memo[(i, j)]
if j == len(p):
return i == len(s)
first_match = i < len(s) and p[j] in {s[i], '.'}
if j + 1 < len(p) and p[j+1] == '*':
# Two options:
# 1. Ignore the "x*" pattern (move j by 2, keep i same)
# 2. Use the "x*" pattern (move i by 1, keep j same - only if first_match is true)
ans = dp(i, j+2) or (first_match and dp(i+1, j))
else:
ans = first_match and dp(i+1, j+1)
memo[(i, j)] = ans
return ans
return dp(0, 0)
This looks correct and covers the standard constraints.
Refinement:
I should probably wrap this in a nice script with example usage.
I will also explain the logic:
. : wildcard
* : zero or more of previous
Base case: pattern ended.
Memoization table.
What if the user meant "Build a Regex Engine from scratch"? That usually implies tokenizing the regex, building an AST, converting to NFA, simulating NFA. That is significantly more complex.
Given the phrasing "regular expression matching algorithm", it almost 99% refers to the Dynamic Programming problem (LeetCode 10). I will focus on that but add a note about full engines.
Let's provide the solution in Python.
Structure:
Introduction: Clarify that this implements a matcher for . and *.
The Approach: Recursive Dynamic Programming (Memoization).
The Code: The Python function.
Explanation: Walk through the if branches.
Example: Run a few test cases.
Let's double check edge cases.
s = "aa", p = "a" -> False.
s = "aa", p = "a*" -> True.
s = "ab", p = ".*" -> True.
s = "aab", p = "c*a*b" -> True.
The logic holds.
Is there a more efficient way? Bottom-up DP uses O(MN) space and O(MN) time. Top-down is effectively the same. The recursive solution is easier to read for most people than a 2D matrix manipulation.
I will write the final response based on this thought process.
Here is a complete implementation of a Regular Expression Matcher in Python.
This solution implements the classic algorithm often referred to as the "LeetCode 10" solution. It supports standard syntax:
Exact match: Matching a specific character.
. (Dot): Matches any single character.
* (Star): Matches zero or more of the preceding element.
The Code (Python)
We use Recursion with Memoization (Dynamic Programming) to ensure the algorithm runs efficiently, even with complex patterns.
python
import functools
class RegexMatcher:
def is_match(self, text: str, pattern: str) -> bool:
"""
Returns True if the text matches the pattern entirely.
"""
# functools.cache automatically memoizes the results of this function
# based on the input indices (i, j). This prevents re-calculating
# the same sub-problems (Time Complexity O(T*P)).
@functools.cache
def dp(i: int, j: int) -> bool:
# Base Case: If we have reached the end of the pattern
if j == len(pattern):
# Return True only if we have also reached the end of the text
return i == len(text)
# Check if the current characters match (or if pattern has a '.')
# We must ensure we haven't run out of text (i < len(text))
first_match = i < len(text) and pattern[j] in {text[i], '.'}
# Optimization: Look ahead to see if the NEXT character is a '*'
if (j + 1) < len(pattern) and pattern[j+1] == '*':
# Two possibilities for a '*':
# 1. Zero occurrences: Skip the "x*" pattern entirely -> dp(i, j+2)
# 2. One or more occurrences: If first chars match, consume text char -> dp(i+1, j)
return dp(i, j + 2) or (first_match and dp(i + 1, j))
else:
# Standard match: Consume one char from both text and pattern
return first_match and dp(i + 1, j + 1)
# Start the recursion from the beginning of both strings
return dp(0, 0)
# --- Usage Examples ---
if __name__ == "__main__":
matcher = RegexMatcher()
test_cases = [
("aa", "a", False), # 'a' doesn't match 'aa'
("aa", "a*", True), # 'a*' matches 'aa'
("ab", ".*", True), # '.*' matches anything
("aab", "c*a*b", True), # 'c*' is 0 'c's, 'a*' is 2 'a's, 'b' is 'b'
("mississippi", "mis*is*p*.", False)
]
print(f"{'Text':<15} | {'Pattern':<10} | {'Result':<6} | {'Expected'}")
print("-" * 50)
for text, pattern, expected in test_cases:
result = matcher.is_match(text, pattern)
status = "PASS" if result == expected else "FAIL"
print(f"{text:<15} | {pattern:<10} | {str(result):<6} | {expected} ({status})")
How it Works
The algorithm works by breaking the problem down into smaller sub-problems defined by two indices: i (position in text) and j (position in pattern).
The first_match Check:
We check if the current characters line up. This is True if text[i] == pattern[j] or if pattern[j] is a dot . (wildcard).
Handling the Star *:
This is the tricky part of Regex logic. A star * always refers to the character immediately preceding it (e.g., in a*, the star applies to a).
Rather than looking backward, it is algorithmically easier to look ahead. If we see that pattern[j+1] is a *, we have two choices:
Option A (Zero matches): We ignore the char* combination entirely. We jump the pattern index by 2: dp(i, j+2).
Option B (One or more matches): If first_match is true, we consume the current character from the text but keep the pattern index at the star (so we can match the same character again if needed): dp(i+1, j).
Memoization (@functools.cache):
Without caching, the function would recalculate the same index pairs (i, j) many times, leading to exponential time complexity (Time Limit Exceeded on large inputs). The @functools.cache decorator stores the result of every (i, j) call, turning the solution into Dynamic Programming with a time complexity of roughly O(T×P), where and are the lengths of the text and pattern.