Wildcard Matching
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
分析:一个超时版本如下:
class Solution { public: bool isMatch(const char *s, const char *p) { if(*s == '\0') return *p == '\0'; if(*p == '\0') return *s == '\0'; int i = 0, j = 0; for(; *(s+i) != '\0' && *(p+j) != '\0';){ if(*(s+i) == *(p+j) || *(p+j) == '?'){ i++; j++; }else if(*(p+j) == '*'){ while(*(s+i) != '\0'){ if(isMatch(s+i, p+j+1)) return true; i++; } return false; }else return false; } return *(s+i) == *(p+j); } };
迭代版本相比递归版本要快,但难度要大。这里参考leetcode.pdf的解答,用两套指针(str,ptr)和(s,p)。(str,ptr)用于探索,(s,p)用于保存探索前的状态,一遍当探索失败后恢复到原来状态。同时要注意一些细节的处理,比如多个连续的'*'。
class Solution { public: bool isMatch(const char *s, const char *p) { bool star = false; const char *str, *ptr; for(str = s, ptr = p; *str != '\0'; str++, ptr++){ switch(*ptr){ case '?': break; case '*': star = true; s = str, p = ptr; while(*p == '*')p++; if(*p == '\0') return true; str = s-1; ptr = p-1; break; default: if(*str != *ptr){ if(!star) return false; s++; str = s-1; ptr = p-1; } } } while(*ptr == '*')ptr++; return *ptr == '\0'; } };