KatInterview

Full-String Matching with Dot and Star Wildcards

Dynamic ProgrammingAuto-graded · 23 test cases
HardAuto-gradedDynamic Programmingdynamic-programmingstringspattern-matching

Last updated

Decide whether a whole text matches a pattern with '.' and '*' wildcards, using prefix-based dynamic programming over text and pattern positions.

Wildcard Pattern Matcher

You are given a text text and a pattern pattern. Write a function that decides whether the pattern matches the entire text. Matching a prefix or a substring is not enough.

The pattern is made of lowercase letters and two special symbols:

  • . stands for exactly one arbitrary character.
  • * applies to the element immediately before it (a letter or .) and means that element may appear zero or more times in a row.

A pattern element followed by * is treated as a single unit. For example, a* can produce "", "a", "aa", and so on, and .* can produce any string, including the empty one.

Return True if the whole text can be produced by the pattern, otherwise False.

Malformed patterns

The input is guaranteed to give every * a valid preceding element. If a pattern ever violates this (it starts with *, or has two * in a row), return False, even when the text is empty.

Constraints

  • 0 <= len(text) <= 20
  • 0 <= len(pattern) <= 20
  • text contains only lowercase English letters.
  • pattern contains only lowercase English letters, . and *.
  • Every * in pattern is guaranteed to have a valid preceding element to repeat.

Examples

Example 1

Input: is_full_match('aa', 'a')

Output: False

Example 2

Input: is_full_match('aa', 'a*')

Output: True

Example 3

Input: is_full_match('ab', '.*')

Output: True

Hints

Hint 1

Think of the state as a pair (i, j): does the first i characters of the text match the first j characters of the pattern? Build a table over these pairs.

Hint 2

Treat `x*` as one unit. When the last pattern character is `*`, you either use zero copies of the preceding element (skip two pattern characters) or use one more copy to absorb the last text character (stay on the same pattern position, drop one text character).

Hint 3

An empty text can still match a pattern like `a*b*c*`. Fill the first row of the table by letting each `x*` pair collapse to nothing, and a greedy left-to-right scan will fail on cases like text `aaa` with pattern `a*a`.