Link: https://leetcode.com/problems/wildcard-matching/
Solution:
Topics: DP
Intuition
This is a great, but quite tricky DP problem. Initially, I understood “sequence” to mean a subarray that is homogenous…for example aaaa or bbb
, but the correct meaning is ANY sequence…which greatly simplifies the problem.
The key to this problem is understanding that the exact sequence consumed by a star is unknown, and cannot be selected greedily…which means all possibilities must be considered.
This problem can be interpreted in terms of subsequences…namely we are looking for the subsequence of characters consumed by stars that allow for a match.
The recursion is structured as follows:
- If we encounter an english character in
p
, it MUST match with the current character ins
- If we encounter a
?
in p, we MUST match it with the current character ins
(any). - If we encounter a
*
in p, we can use it or not use it, or continue using it. - If we reach the end of
s
and the end ofp
(or if remaining chars in p are stars), we return true.
Implementation