Skip to main content
Back to problems
Leetcode
Hard
Strings
Dynamic Programming
Recursion
Google
Amazon
Microsoft
Regular Expression Matching

Determine whether a string matches a simplified regular expression supporting '.' and '*'.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Regex Matching

gfg
Problem Statement

Problem

Given an input string s and a pattern p, determine whether the entire string matches the entire pattern.

The pattern uses a simplified regular expression syntax:

  • . matches any single character.
  • * means the preceding element can appear zero or more times.

You must return true only if all characters in s are consumed and the pattern matches the whole string.

Notes

  • * always applies to the character immediately before it.
  • Matching is for the entire string, not a substring.
  • The pattern is guaranteed to be valid for this simplified syntax.

Input Format

  • A string s
  • A pattern p containing lowercase letters, . and *

Output Format

Return true if s matches p exactly; otherwise return false.

Constraints

  • 0 <= s.length, p.length <= 2000
  • s contains lowercase English letters only
  • p contains lowercase English letters, . and *
  • The pattern is valid and * always follows a valid preceding token
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "aa", p = "a"

Output

false

Explanation

The pattern a can only match one character, but s has two.

Example 2

Input

s = "aa", p = "a*"

Output

true

Explanation

* allows the preceding a to repeat, so a* can match aa.

Show 1 more example

Example 3

Input

s = "ab", p = ".*"

Output

true

Explanation

. matches any character, and * allows it to repeat enough times to consume the whole string.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.