Tutorialspoint
Problem
Solution
Submissions

Regular Expression Matching

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program to implement regular expression matching with support for '.' and '*' where:
- '.' Matches any single character.
- '*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).

Example 1
  • Input: s = "aa", p = "a*"
  • Output: true
  • Explanation:
    • '*' means zero or more of the preceding element, 'a'.
    • Therefore, by repeating 'a' once, it becomes "aa".
Example 2
  • Input: s = "mississippi", p = "mis*is*p*."
  • Output: false
  • Explanation:
    • The pattern doesn't match the entire string because the final '.' needs to match the last 'i' in "mississippi".
    • But there's still a 'p' and 'i' left unmatched.
Constraints
  • 1 ≤ s.length ≤ 20
  • 1 ≤ p.length ≤ 30
  • s contains only lowercase English letters
  • p contains only lowercase English letters, '.', and '*'
  • Time Complexity: O(m*n) where m and n are lengths of string and pattern
  • Space Complexity: O(m*n)
ArraysDynamic Programming PwCD. E. Shaw
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 DP table where dp[i][j] represents if s[0...i-1] matches p[0...j-1]
  • Handle the special case of '*' which can match zero or more of the preceding character
  • Initialize the base cases carefully, especially for empty strings
  • Consider all possible pattern combinations when '*' is involved

Steps to solve by this approach:

 Step 1: Create a 2D DP table where dp[i][j] represents if the first i characters of s match the first j characters of p.
 Step 2: Initialize dp[0][0] = true since empty pattern matches empty string.
 Step 3: Handle the case where pattern might match empty string (like a*, a*b*, etc.).
 Step 4: For each character in the string and pattern, analyze different matching scenarios.
 Step 5: If the current pattern character is '*', it can either match zero of the preceding element (dp[i][j-2]) or match one or more of the preceding element if it matches the current string character.
 Step 6: If the current pattern character is '.' or matches the current string character, the result depends on the match status of the previous characters.
 Step 7: Return dp[m][n] which represents if the entire string matches the pattern.

Submitted Code :