一、Problem
Given an input string (s) and a pattern §, 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 *.
Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
Input:
s = "acdcb"
p = "a*c?b"
Output: false
二、Solution
方法一:dp
经典串匹配,只不过加了几个约束条件…
- 定义状态:
- 表示 s 的前 个字符能否用 p 的前 个字符进行匹配,这样比较好理解
- 思考初始化:
- ,当 s 为空串时,p 的前 个字符只有是 * 号时,才能用 p 进行匹配;? 不行是因为 ? 只能匹配单个字符
- 思考状态转移方程:
- 如果 或者 但 ,则有
- 如果 ,则 * 有两种作用:
- 当做空串进行匹配(ac, ac*),
- 当做有意义的字符串(acac, ac*),由上可得,因为 ,所以
- 综上,
- 思考输出:
class Solution {
public:
bool isMatch(string s, string p) {
int n = s.size(), m = p.size();
vector<vector<bool>> f(n+1, vector<bool>(m+1)); f[0][0] = true;
for (int j = 1; j <= m; j++) if (p[j-1] == '*') {
f[0][j] = f[0][j-1];
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
if (s[i-1] == p[j-1] || p[j-1] == '?') {
f[i][j] = f[i-1][j-1];
} else if (p[j-1] == '*') {
f[i][j] = f[i][j-1] || f[i-1][j];
}
}
return f[n][m];
}
};
复杂度分析
- 时间复杂度:,
- 空间复杂度:,