Regular Expression Matching Leetcode Solution

Regular Expression Matching Leetcode Problem

Given an input string s and a pattern p, 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).
Regular expression matching

Regular Expression Matching Leetcode Solution :

Constraints :

  • 1 <= s.length <= 20
  • 1 <= p.length <= 20
  • 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.

Example 1:

Input: s = “aa”, p = “a*”

Output: true

Example 2:

Input: s = “ab”, p = “.*”

Output: true

In the “Two Sum” problem, you are given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:

  • '.' Matches any single character.
  • '*' Matches zero or more of the preceding element.

Approach :

For Solving two sum Leetcode Problem we can use following procedure :

  • If the pattern is empty, return True if the text is also empty (base case).
  • Check if the first characters of the text and pattern match, considering ‘.’ as a wildcard character.
  • If the next character in the pattern is ”, there are two possibilities:
    a. Ignore the ” and the preceding character in the pattern and continue matching the text with the shortened pattern.
    b. Keep the preceding character in the pattern and match the next character in the text.
  • If there is no ‘*’ in the pattern, simply match the next characters in the text and pattern.
Regular expression matching

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription