CodingNodes / 2-D Dynamic Programming / Regular Expression Matching System design Space play · ←→ step · R restart

Problem

You are given a text s and a pattern p. The pattern may contain two special symbols:

  • . matches any single letter,
  • * matches zero or more copies of the symbol just before it.

Return true if the pattern matches the whole text, and false otherwise.

Constraints

  • 1 ≤ s.length ≤ 20 and 1 ≤ p.length ≤ 20
  • s has only lowercase English letters
  • p has lowercase letters, . and *
  • every * follows a letter or a dot, so a pattern never starts with *

Examples: pick one to animate

Solutions

TimeO(m · n) SpaceO(m · n)

Time: The table has (m + 1) · (n + 1) cells and each one is filled from at most two earlier cells in constant time.

Space: The full table of (m + 1) · (n + 1) true or false values is stored.

Let dp[i][j] be true when the first i letters of s match the first j symbols of p. Only dp[0][0] starts true. For a normal symbol or a dot, the cell copies the diagonal when the letter fits. For a star, first allow zero copies by copying the cell two to the left. If the symbol before the star fits the current letter, also allow one more copy: the cell above, in the same column, may make it true.