Skip to content
Decoder

Regular Expression Matching

Hard

Problem

Implement a tiny regular expression matcher. The pattern p contains lowercase letters plus two special characters:

- . matches any single character. - * means zero or more of the preceding element.

Return true if p matches the entire string s (not just part of it).

Example 1

Input
s = "aa", p = "a"
Output
false
Why
only one a

Example 2

Input
s = "aa", p = "a*"
Output
true

Example 3

Input
s = "ab", p = ".*"
Output
true
Why
any characters, any number of times

Example 4

Input
s = "aab", p = "c*a*b"
Output
true
Why
zero c's, two a's, one b

Constraints

  • 1 <= s.length <= 20
  • 1 <= p.length <= 20
  • s contains only lowercase letters; p contains lowercase letters, . and *.
  • Every * comes right after a letter or ..

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.