KatInterview

Full-String Matching With Single and Multi Character Wildcards

Dynamic ProgrammingAuto-graded · 28 test cases
MediumAuto-gradedDynamic Programmingstringswildcard-matchingdynamic-programming

Last updated

Decide whether a pattern containing '?' and '*' wildcards matches an entire string, testing dynamic programming or greedy two-pointer matching with backtracking.

Wildcard Pattern Check

You are given a string s and a pattern pat. Decide whether pat matches all of s, not just a part of it.

The pattern may contain letters and two special symbols:

  • ? stands for exactly one character, any character at all.
  • * stands for any run of characters, of any length, including a run of length zero.

Every other character in the pattern stands only for itself.

Return True if the whole of s can be produced by expanding the wildcards in pat, and False otherwise.

Details

  • If both s and pat are empty, the answer is True.
  • A run of several consecutive * symbols behaves exactly like a single *.
  • An empty pat matches only an empty s.
  • A ? needs one character to consume, so it never matches an empty string.

Constraints

  • 0 <= len(s) <= 1000
  • 0 <= len(pat) <= 1000
  • s contains only lowercase English letters.
  • pat contains only lowercase English letters, ?, and *.

Examples

Example 1

Input: wildcard_match('aa', '*')

Output: True

Example 2

Input: wildcard_match('cb', '?a')

Output: False

Example 3

Input: wildcard_match('adceb', '*a*b')

Output: True

Example 4

Input: wildcard_match('', '')

Output: True

Hints

Hint 1

Think of the question as: does the suffix s[i:] match the suffix pat[j:]? Write down what each kind of pattern character (letter, '?', '*') implies for the next state.

Hint 2

A '*' has two options: match nothing (advance only in the pattern) or swallow one more character of s (advance only in s). Many different paths reach the same (i, j) pair, so cache or tabulate the results.

Hint 3

For an O(1)-space approach, remember only the most recent '*' and the position in s where its match currently ends. On a mismatch, jump back to just after that star and let it absorb one more character; earlier stars never need to be revisited.