
Problem
Solution
Submissions
Regular Expression Matching using DP
Certification: Advanced Level
Accuracy: 50%
Submissions: 6
Points: 15
Write a Java program to implement regular expression matching with support for '.' and '*'. The matching should cover the entire input string, not just a portion of it.
- '.' Matches any single character.
- '*' Matches zero or more of the preceding element.
Example 1
- Input: s = "aa", p = "a*"
- Output: true
- Explanation:
- The pattern "a*" means zero or more occurrences of 'a'.
- The first 'a' in "aa" matches the 'a' in the pattern, and the second 'a' can be matched by the '*', which allows 'a' to appear multiple times.
Example 2
- Input: s = "mississippi", p = "mis*i.*pi"
- Output: true
- Explanation:
- The first three characters "mis" match directly. The pattern "s*" matches the single 's'.
- The 'i' matches the next 'i' in the string. The pattern ".*" matches any sequence of characters, which in this case is "ssi".
- The remaining "pi" in the pattern matches the final "pi" in 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 for each appearance of the character '*', there will be a previous valid character to match
- Time Complexity: O(m*n) where m and n are the lengths of the string and pattern respectively
- Space Complexity: O(m*n)
Editorial
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. |
Solution Hints
- Use dynamic programming to solve this problem
- Create a 2D boolean array dp[m+1][n+1] where dp[i][j] indicates if the first i characters of s match the first j characters of p
- Handle the base cases properly: empty string and empty pattern
- When you encounter a '*' in the pattern, you need to consider both zero occurrence and multiple occurrences of the preceding character
- When you encounter a '.', it matches any single character in the string
- Be careful with edge cases, especially those involving '*' at the beginning of patterns