Wildcard Matching

Wildcard Matching

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).

Note:

s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like ? or *. Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

Example 4:

Example 5:

Analysis

Dynamic Programming

Similar to Regular Expression Matching, the difference is how the '*', '?' are interpreted, also it uses '?' instead of '.'

Yet the fundamentals are the same, just the initialization and state transfer function needs to be modified.

Multi-Pointers Approach https://leetcode.com/problems/wildcard-matching/discuss/17810/Linear-runtime-and-constant-space-solution

Although it might be easier to think of DP solution if you've met Regular Expression Matching problem before, there's a more straightforward approach that's more intuitive.

Solution

DP - O(mn) space, O(mn) time - (33ms 76% AC)

Multi-Pointers - O(1) space, O(mn) time

Last updated

Was this helpful?