Tutorialspoint
Problem
Solution
Submissions

Regular Expression Matcher

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 10

Write a Python function to implement a simple regular expression matcher with support for '.' and '*'.

Example 1
  • Input: text = "aa", pattern = "a*"
  • Output: true
  • Explanation:
    • Step 1: '*' allows 'a' to repeat 0 or more times.
    • Step 2: Pattern "a*" matches "aa".
Example 2
  • Input: text = "abc", pattern = "a.c"
  • Output: true
  • Explanation:
    • Step 1: '.' matches any character.
    • Step 2: Pattern "a.c" matches "abc" because '.' matches 'b'.
Constraints
  • 1 ≤ text.length ≤ 20
  • 1 ≤ pattern.length ≤ 30
  • pattern contains only lowercase English letters, '.', and '*'
  • Time Complexity: O(m * n), where m and n are the lengths of pattern and text
  • Space Complexity: O(m * n)
ArraysDynamic Programming FacebookShopify
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming to solve this problem
  • Create a 2D boolean array to store whether substrings of text match subpatterns
  • Handle the special cases of '*' and '.' carefully
  • Base case: empty pattern matches empty text
  • Work through the pattern character by character, handling regular characters, dots, and stars differently

Steps to solve by this approach:

 Step 1: Create a 2D DP table where dp[i][j] represents if the first i characters of text match the first j characters of pattern.
 Step 2: Set base case dp[0][0] = True (empty text matches empty pattern).
 Step 3: Handle the special case where pattern contains '*' that can match empty string.
 Step 4: Fill the table by checking character matches and applying the appropriate logic for '.', and '*'.
 Step 5: Return dp[len(text)][len(pattern)] which indicates if the entire text matches the entire pattern.

Submitted Code :