【leetcode】44.Wildcard Matching(通配符匹配)
Given an input string (s) and a pattern (p), 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 *.
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.
Example 3:
Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Example 4:
Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
Example 5:
Input:
s = "acdcb"
p = "a*c?b"
Output: false
给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?' 和 '*' 的通配符匹配。
'?' 可以匹配任何单个字符。
'*' 可以匹配任意字符串(包括空字符串)。
两个字符串完全匹配才算匹配成功。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。
示例 1:
输入:
s = "aa"
p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。
示例 2:
输入:
s = "aa"
p = "*"
输出: true
解释: '*' 可以匹配任意字符串。
示例 3:
输入:
s = "cb"
p = "?a"
输出: false
解释: '?' 可以匹配 'c', 但第二个 'a' 无法匹配 'b'。
示例 4:
输入:
s = "adceb"
p = "*a*b"
输出: true
解释: 第一个 '*' 可以匹配空字符串, 第二个 '*' 可以匹配字符串 "dce".
示例 5:
输入:
s = "acdcb"
p = "a*c?b"
输入: false
思路:
题意分析:
做法与 10. Regular Expression Matching(正则表达式匹配) 类似:
- 以
dp[i][j]
表示p[0...i-1]
与s[0...j-1]
能匹配 - 当
p[i]==s[j]
或p[i]=='?'
或p[i] == '*'
时,dp[i+1][j+1] = 1
dp[i+1][j+1] = dp[i][j] && (p[i]==s[j] || p[i]=='?' || p[i]=='*')
- 特殊处理 ‘*’ 的情况:
I. 取 0,抹除 p[i],则 dp[i+1][...] = dp[i][...]
dp[i+1][...] = dp[i][...]
II. 取 infinite,如果前一个能够匹配 p[i]==s[j-1] ,则 s[j] 可以继续匹配:
dp[i+1][j+1] = dp[i][j] && (p[i]==s[j] || p[i]=='?' || p[i]=='*') || dp[i+1][j] && p[i]=='*'
- 同样,只是依赖前一组数据,最少只需要申请
2 * (slen+1)
的内存即可。
CODE:
class Solution {
public:
bool isMatch(string s, string p) {
int slen = s.length();
int plen = p.length();
vector<vector<int>> dp(2, vector<int>(slen+1));
dp[0][0] = 1;
int pre_idx = 0, cur_idx = 1;
for (int i = 0; i < plen; ++i) {
char ch = p[i];
int cnt = 0;
if (ch=='*') {
for (int j=0; j<=slen; ++j) {
dp[cur_idx][j] = dp[pre_idx][j];
}
cnt = 1;
} else {
memset(&dp[cur_idx][0], 0, sizeof(int) * (slen+1));
}
for (int j = 0; j < slen; ++j) {
if ((dp[pre_idx][j] && (ch == s[j] || ch == '?' || ch == '*'))
|| (dp[cur_idx][j] && ch == '*')) {
dp[cur_idx][j+1] = 1;
cnt = 1;
}
}
if (!cnt) return false;
pre_idx = cur_idx;
cur_idx = 1 - cur_idx;
}
return dp[pre_idx][slen];
}
};