Full-String Matching With Single and Multi Character Wildcards
Dynamic ProgrammingAuto-graded · 28 test casesLast 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
sandpatare empty, the answer isTrue. - A run of several consecutive
*symbols behaves exactly like a single*. - An empty
patmatches only an emptys. - A
?needs one character to consume, so it never matches an empty string.
Constraints
0 <= len(s) <= 10000 <= len(pat) <= 1000scontains only lowercase English letters.patcontains 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walk through s and pat together with two pointers. Whenever the pattern shows a *, remember two things:
star_pos: the index of that star in the pattern.resume_si: the position inswhere the star's match currently ends (initially it matches the empty string).
At each step:
- If the current pattern character is
?or equals the current character ofs, advance both pointers. - Otherwise, if the current pattern character is
*, record it as the latest star, let it match nothing for now, and move past it in the pattern. - Otherwise (a mismatch), if a star has been seen, rewind the pattern pointer to just after that star, make the star swallow one more character of
s, and continue from there. - Otherwise, there is no star to fall back on, so the answer is
False.
When s is used up, any remaining pattern must consist only of * characters (each matching the empty string). Skip them and succeed only if the whole pattern has been consumed.
Why it is correct
Split the pattern at its stars into star-free segments. A match exists exactly when these segments can be placed in s in order, without overlapping, with the first anchored at the start and the last anchored at the end.
- Earliest placement is safe. Placing a segment at its earliest feasible position leaves the most room for later segments, and the star after it can absorb any skipped characters.
- Only the latest star needs to change. If a mismatch occurs while matching the segment after the latest star, letting an earlier star absorb more would only shift the latest star's region later, which that star could already do itself.
- No star yet means the mismatch is final, since the leading segment must match literally.
- Consecutive stars need no special case: each new star simply overwrites the recorded one, which is equivalent to a single star.
Complexity
- Time: O(len(s) * len(pat)) in the worst case, typically close to linear.
- Space: O(1).
Reference solution
def wildcard_match(s: str, pat: str) -> bool:
si = 0
pi = 0
star_pos = -1
resume_si = 0
while si < len(s):
if pi < len(pat) and (pat[pi] == '?' or pat[pi] == s[si]):
si += 1
pi += 1
elif pi < len(pat) and pat[pi] == '*':
star_pos = pi
resume_si = si
pi += 1
elif star_pos != -1:
pi = star_pos + 1
resume_si += 1
si = resume_si
else:
return False
while pi < len(pat) and pat[pi] == '*':
pi += 1
return pi == len(pat)