首页 > 代码库 > Wildcard Matching
Wildcard Matching
1. recursion
1 class Solution { 2 public: 3 bool isMatch(const char *s, const char *p) { 4 if(s == NULL || p == NULL) return false; 5 if(*p == ‘\0‘) return *s == ‘\0‘; 6 7 if((*p == *s) || (*p == ‘?‘ && *s != ‘\0‘)){ 8 return isMatch(s + 1, p + 1); 9 }10 else if(*p == ‘*‘){11 while(*p == ‘*‘) p++;12 if(*p == ‘\0‘) return true;13 else{14 while(*s != ‘\0‘){15 if(isMatch(s,p)) return true;16 s++;17 }18 }19 }20 return false;21 }22 };
status: Time Limit Exceeded
2. dynamic programming
1 class Solution { 2 public: 3 bool isMatch(const char *s, const char *p) { 4 if(s == NULL || p == NULL) return false; 5 int ls, lp; 6 for (ls = 0; *(s + ls) != ‘\0‘; ls++); 7 for (lp = 0; *(p + lp) != ‘\0‘; lp++); 8 if(ls == 0){ 9 const char *tmp = p;10 while(*tmp == ‘*‘) tmp++;11 return *tmp == ‘\0‘;12 }13 if(lp == 0) return *s == ‘\0‘;14 15 bool *a = new bool[lp]();16 for (int i = 0; i < lp; i++) a[i] = true;17 18 bool *b = new bool[lp](); 19 for (int t = 0; t < ls; t++){20 if(a[0] == true && *p == ‘*‘) b[0] = true;21 else b[0] = false;22 for (int j = 1; j < lp; j++){23 if((a[j] == true && *(p + j) == ‘*‘) || (a[j - 1] == true && (*(s + t) == *(p + j) || *(p + j) == ‘?‘))) b[j] = true;24 else b[j] = false;25 }26 copy(a,b,lp);27 }28 return a[lp];29 }30 void copy(bool *a, bool *b, const int n){ 31 for(int i = 0; i < n; i++){32 a[i] = b[i];33 }34 } 35 };
status: Time Limit Exceeded
3. greedy
1 class Solution { 2 public: 3 bool isMatch(const char *s, const char *p) { 4 const char *pp = NULL; 5 const char *ss = NULL; 6 while(*s){ 7 if(*s == *p || *p == ‘?‘){ 8 s++; 9 p++;10 continue;11 }12 else if(*p == ‘*‘){13 pp = p;14 p++;15 ss = s;16 continue;17 }18 else if(pp != NULL){19 p = pp + 1;20 ss++;21 s = ss;22 continue;23 }24 return false;25 }26 while(*p == ‘*‘) p++;27 return *p == ‘\0‘;28 }29 };
Wildcard Matching
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。