Wildcard Matching — LeetCode 44 Python Solution
- Problem
- #44
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence).
Example
- Input
- s = "aa", p = "a"
- Output
- false
- Explanation
- "a" does not match the entire string "aa".
Python solution
class Solution:
def isMatch(self, s: str, p: str) -> bool:
@cache
def dfs(i: int, j: int) -> bool:
if i >= len(s):
return j >= len(p) or (p[j] == "*" and dfs(i, j + 1))
if j >= len(p):
return False
if p[j] == "*":
return dfs(i + 1, j) or dfs(i + 1, j + 1) or dfs(i, j + 1)
return (p[j] == "?" or s[i] == p[j]) and dfs(i + 1, j + 1)
return dfs(0, 0)Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(m \times n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 44. Wildcard Matching is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 44. Wildcard Matching?
- LeetCode 44. Wildcard Matching is rated Hard on LeetCode.
- What is the time complexity of LeetCode 44. Wildcard Matching?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 44. Wildcard Matching?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 44. Wildcard Matching cover?
- LeetCode 44. Wildcard Matching is tagged Greedy, Recursion, String and Dynamic Programming on LeetCode.