Tutorialspoint
Problem
Solution
Submissions

Regular Expression Matching

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

Write a C program to implement regular expression matching with support for '.' and '*'. Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where '.' matches any single character and '*' matches zero or more of the preceding element.

Example 1
  • Input: s = "aa", p = "a"
  • Output: false
  • Explanation: Pattern "a" matches only one 'a'. String "aa" has two 'a' characters. Therefore, pattern does not match the string
Example 2
  • Input: s = "aa", p = "a*"
  • Output: true
  • Explanation: Pattern "a*" means zero or more 'a' characters. String "aa" has exactly two 'a' characters. Therefore, pattern matches the string
Constraints
  • 1 ≤ s.length ≤ 20
  • 1 ≤ p.length ≤ 30
  • s contains only lowercase English letters
  • p contains only lowercase English letters, '.', and '*'
  • It is guaranteed that for each appearance of '*', there will be a previous valid character to match
  • Time Complexity: O(m*n) where m and n are lengths of string and pattern
  • Space Complexity: O(m*n)
StringsDynamic Programming GoogleIBM
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 efficiently
  • Create a 2D DP table where dp[i][j] represents if s[0...i-1] matches p[0...j-1]
  • Handle base cases: empty string and empty pattern
  • For '*', consider two cases: match zero characters or match one or more characters
  • For '.', it can match any single character

Steps to solve by this approach:

 Step 1: Create a 2D DP table of size (m+1) x (n+1) where m and n are string and pattern lengths
 Step 2: Initialize base case: empty string matches empty pattern (dp[0][0] = true)
 Step 3: Handle patterns that can match empty string (patterns ending with '*')
 Step 4: Fill the DP table by comparing each character of string with pattern
 Step 5: For '*', consider both zero matches and one-or-more matches cases
 Step 6: For '.', treat it as matching any character
 Step 7: Return the value at dp[m][n] which represents full string matching full pattern

Submitted Code :