Problem
Problem page: https://leetcode.com/problems/wildcard-matching/
Topics: Dynamic Programming, Backtracking, Greedy, String
Difficulty: Hard
Similar problems: (H) Regular Expression Matching
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). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "*") → true isMatch("aa", "a*") → true isMatch("ab", "?*") → true isMatch("aab", "c*a*b") → false
Analysis
The special test cases in this DP problem gave me far more trouble than the complexity of the algorithm itself. Before this, when I optimized DP algorithms, I focused on saving space. It didn't occur to me that I could spot some cases early or preprocess them to cut the running time. Without that, I'd keep getting Time Limit Exceeded on some really long, nasty cases.
- During preprocessing, I can replace each run of consecutive * in the pattern p with a single *.
- If the total number of question marks and ordinary characters in the pattern is greater than the length of the string s, the match fails.
- If s is empty, the match succeeds if the pattern is empty or contains only *. Otherwise, the match fails.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-wildcard-matching/
