44. Wildcard Matching
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 *.
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
Approach
题目大意: 字符串模式匹配,‘*’可以匹配任意长度的序列,包括长度为零,‘?’匹配任意一个单词
解题思路:有两种解题,一种是用递归回溯求解,需要适当剪枝。第二种是用迭代求解,有点类似AC自动机,保存上一次的状态。贴出的代码就是第二种思路,我们通过保存 p[j]==*
此时的j的索引,然后继续判断下去,如果匹配不成功,恢复到上一次,将s的i
的索引尝试加一个递增的数。
Code
class Solution {
public:
bool isMatch(string s, string p) {
int n = s.size(), m = p.size();
if (n == 0 && m == 0)return true;
int i = 0, j = 0, star = 0, txt = -1;
while (i < n) {
if (j < m && (p[j] == '?' || s[i] == p[j])) {
j++, i++;
} else if (j < m && p[j] == '*') {
txt = j++;
star = i;
} else if (txt >= 0) {
j = txt + 1;
i = ++star;
} else {
return false;
}
}
while (j < m && p[j] == '*')j++;
return j == m;
}
};