44. Wildcard Matching
'?' 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
一般来讲递归必然超时,于是乎就选择用循环做。
思路:由于?只匹配一个字符,因此它可以和正常的匹配归为一类
遇到*号时,记录星号的位置,用星号后面的第一个字符去匹配标准匹配中的已经匹配成功的后一个,从这个后一个开始往后寻找能和星号后第一个匹配的字符,如果找到了,就继续按照标准匹配一个一个匹配,如果没有而且此时没有在等待匹配的*号 则匹配失败,如果匹配字符串结束了,从被匹配字符串开始找寻*号 如果出现非*号 且非结束符的则返回失败,否则返回成功。
bool isMatch(char* s, char* p) {
char* star = NULL;
char* rs = NULL;
while(*s) {
if(*s == *p || *p == '?') {
s++; p++;
continue;
}
if(*p == '*') {
star = p;
p++;
rs = s;
continue;
}
if(star != NULL) {
p = star + 1;
s = rs + 1;
rs ++;
continue;
}
return false;
}
while(*p == '*') p++;
return *p == '\0';
}