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).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
此算法在leetcode上实际执行时间为 27ms。
class Solution {
public:
bool isMatch(const char *s, const char *p) {
const char *star = 0;
const char *ss = 0;
while (*s) {
if (*p == *s || *p == '?') {
++p;
++s;
}
else if (*p == '*') {
star = p++;
ss = s;
}
else if (star) {
p = star;
s = ++ss;
}
else
return false;
}
while (*p == '*') ++p;
return !*p;
}
};
主要是对’*’的处理。
1.遇到’*’,首先偿试匹配0个。即不消耗当前s的字符。用p后续的匹配串,去对s进行匹配。
2.如果失败,则消耗掉当前s的字符。
此题用递归写的法,比较容易,但是在时间上很难被AC。原因在于递归时回溯的比较多。
此题想要在时间上被AC,要利用一个优化条件:
如果匹配失败,则只用回退最近上一个*处继续进行第2步处理。
参考:
https://oj.leetcode.com/discuss/10133/linear-runtime-and-constant-space-solution