描述
请实现支持'?'and'*'.的通配符模式匹配
'?' 可以匹配任何单个字符。
'*' 可以匹配任何字符序列(包括空序列)。
返回两个字符串是否匹配
函数声明为:
bool isMatch(const char *s, const char *p)
只有p字符串包含通配符
下面给出一些样例:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "d*a*b") → false
数据范围:字符串长度满足 0≤n≤10000 \le n \le 10000≤n≤1000
进阶:空间复杂度 O(1)O(1) O(1),时间复杂度 O(n)O(n)O(n)
示例1
输入:
"ab","?*"
返回值:
true
示例2
输入:
"ab","*"
返回值:
true
class Solution {
public:
bool isMatch(const char *s, const char *p) {
int sLen = strlen(s),sIndex = 0;
int pLen = strlen(p),pIndex = 0;
int ppre = 0,ipre = 0;
bool flag = false;
while (sIndex<sLen) {
if (s[sIndex]==p[pIndex] || p[pIndex]=='?'){
++sIndex,++pIndex;
}else if (p[pIndex]=='*'){ //跳过并记录*后面开始匹配的索引
ppre = ++pIndex;
ipre = sIndex; //记录s中开始与*后面匹配的索引
flag = true;
}else{
if (flag){ //无法匹配,在出现*情况下用*弥补
sIndex = ++ipre;
pIndex = ppre;
}else{
return false;
}
}
}
while (p[pIndex]=='*') { //将剩余的*匹配掉
++pIndex;
}
return pIndex==pLen&&sIndex==sLen;
}
};