Python coding

Match text against dots and stars

Return True if the pattern p matches all of the string s, otherwise False. In p, a letter matches itself, . matches any one character, and * stands for zero or more copies of the item right before it, a letter or a .: b* matches "", "b", "bb" and so on, and .* matches any string. The match must cover the whole of s, not just a part of it.

s has 0 to 100 lowercase letters. p has 0 to 100 characters, all lowercase letters, . or *, and every * comes right after a letter or a .. Aim for O(len(s) · len(p)) time.

Besides the tests, one large input (20 letters, 8 stars) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • matches("abbbc", "ab*c") → true
  • matches("ac", "ab*c") → true
  • matches("ab", ".*c") → false
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Matching left to right breaks at a star: a* may stand for zero copies or many, and an early choice can be wrong. Let the state be (i, j): does s[i:] match p[j:]?

Hint 2

If p[j + 1] is *, either skip the pair (j + 2) or, when s[i] fits p[j], use one copy and stay (i + 1, j). Otherwise s[i] must fit p[j] and both advance.

Hint 3

Plain recursion is exponential on patterns like a*a*a*…c: the same (i, j) is reached in many ways. Cache it, or fill a table from the ends.

Solution and why it works
pythonO(m · n), m = len(s), n = len(p) · O(m · n)
from functools import cache


def matches(s: str, p: str) -> bool:
    @cache
    def fits(i: int, j: int) -> bool:    # does s[i:] match p[j:]?
        if j == len(p):
            return i == len(s)
        first = i < len(s) and p[j] in (s[i], ".")
        if j + 1 < len(p) and p[j + 1] == "*":
            # skip the starred item, or let it eat s[i] and stay on it
            return fits(i, j + 2) or (first and fits(i + 1, j))
        return first and fits(i + 1, j + 1)

    return fits(0, 0)

Each state (i, j) asks whether the rest of s matches the rest of p, and has at most two moves: a starred item matches nothing (skip it) or eats one character and stays. With the cache, each of the (m + 1)(n + 1) states is solved once in O(1). Without it, a*a*a*… tries every way to share the letters among the stars: exponential. Watch the ends: an empty s still matches x*y*, but leftover text never matches an empty pattern.

Related lab: Big-O growth