oneby7

2-D Dynamic Programming Two strings

565. Regular Expression Matching

Hard

You are given a string s and a pattern p. Return true if the pattern matches the whole of s, and false otherwise.

The pattern holds lowercase letters and two special characters:

  • A letter matches that same letter.
  • . matches any one letter.
  • * matches zero or more copies of the character right before it. So a* matches "", "a", "aa" and so on. In .*, each copy of . can be a different letter, so .* matches any string, the empty one included.

The match must cover all of s, from its first letter to its last. A pattern that matches only the start of s does not count.

Example 1

Input: s = "bread", p = "b.*a."

Output: true

Explanation: b matches the b, .* takes "re", a matches the a, and . takes the last letter, d.

Example 2

Input: s = "", p = "x*y*"

Output: true

Explanation: Both x* and y* take zero copies, so the pattern matches the empty string.

Example 3

Input: s = "abb", p = "a*b"

Output: false

Explanation: The pattern matches "ab", the start of s, but the last b is left over. A b with no * after it matches exactly one b.

Check your understanding

Work out the answer for this input before you write any code.

s = "ab", p = "a*"

Constraints

  • 0 ≤ s.length, p.length ≤ 2000
  • s holds only lowercase English letters.
  • p holds only lowercase English letters, . and *.
  • Every * in p comes right after a letter or a ..

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.