LeetCode 题解工作台
通配符匹配
给你一个输入字符串 ( s ) 和一个字符模式 ( p ) ,请你实现一个支持 '?' 和 '*' 匹配规则的通配符匹配: '?' 可以匹配任何单个字符。 '*' 可以匹配任意字符序列(包括空字符序列)。 判定匹配成功的充要条件是:字符模式必须能够 完全匹配 输入字符串(而不是部分匹配)。 示例 1…
4
题型
7
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们设计一个函数 $dfs(i, j)$,表示从字符串 的第 个字符开始和字符串 的第 个字符开始是否匹配。那么答案就是 $dfs(0, 0)$。 函数 $dfs(i, j)$ 的执行过程如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
s) 和一个字符模式 (p) ,请你实现一个支持 '?' 和 '*' 匹配规则的通配符匹配:'?'可以匹配任何单个字符。'*'可以匹配任意字符序列(包括空字符序列)。
判定匹配成功的充要条件是:字符模式必须能够 完全匹配 输入字符串(而不是部分匹配)。
示例 1:
输入:s = "aa", p = "a" 输出:false 解释:"a" 无法匹配 "aa" 整个字符串。
示例 2:
输入:s = "aa", p = "*" 输出:true 解释:'*' 可以匹配任意字符串。
示例 3:
输入:s = "cb", p = "?a" 输出:false 解释:'?' 可以匹配 'c', 但第二个 'a' 无法匹配 'b'。
提示:
0 <= s.length, p.length <= 2000s仅由小写英文字母组成p仅由小写英文字母、'?'或'*'组成
解题思路
方法一:记忆化搜索
我们设计一个函数 ,表示从字符串 的第 个字符开始和字符串 的第 个字符开始是否匹配。那么答案就是 。
函数 的执行过程如下:
- 如果 ,那么只有当 或者 且 为真时, 才为真。
- 如果 ,那么 为假。
- 如果 ,那么 为真当且仅当 或 或 中有一个为真。
- 否则 为真当且仅当 或 且 为真。
为了避免重复计算,我们使用记忆化搜索的方法,将 的结果存储在一个哈希表中。
时间复杂度 ,空间复杂度 。其中 和 分别是字符串 和 的长度。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you correctly handle '*' matching multiple characters without skipping necessary DP states?
- question_mark
Can you optimize space usage while maintaining full string coverage matching?
- question_mark
Will you explain how consecutive '?' and '*' affect your state transitions and edge cases?
常见陷阱
外企场景- error
Failing to initialize the DP table for empty strings or patterns with leading '*' characters.
- error
Mismanaging backtracking when '*' is involved, causing incorrect false negatives.
- error
Overlooking the need to match the entire string, allowing partial matches to incorrectly return true.
进阶变体
外企场景- arrow_right_alt
Matching with additional character classes like [a-z] or numeric ranges in the pattern.
- arrow_right_alt
Wildcard Matching II: pattern allows escape characters and nested wildcards requiring modified DP transitions.
- arrow_right_alt
Minimum edits required to transform string s to match pattern p considering '?' and '*' insertions.