标签:
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
1 class Solution { 2 public: 3 bool isMatch(const char *s, const char *p) { 4 5 if(*s==‘\0‘&&*p==‘\0‘) return true; 6 if(*s!=‘\0‘&&*p==‘\0‘) return false; 7 if(*s==‘\0‘&&*p!=‘\0‘) return false; 8 9 if(*p==‘*‘) 10 { 11 while(*p==‘*‘) p++; 12 13 14 while(*s!=‘\0‘) 15 { 16 if(isMatch(s,p)) return true; 17 s++; 18 } 19 20 return isMatch(s,p); 21 } 22 else if(*p==‘?‘) 23 { 24 return isMatch(s+1,p+1); 25 } 26 else 27 { 28 return (*s==*p&&isMatch(s+1,p+1)); 29 } 30 31 32 return false; 33 } 34 };
1 class Solution { 2 public: 3 bool isMatch(const char *s, const char *p) { 4 5 6 const char* afterStarPositionP=NULL; 7 const char* afterStarPositionS=NULL; 8 while(*s!=‘\0‘) 9 { 10 if(*s==*p||*p==‘?‘) 11 { 12 s++;p++; 13 continue; 14 } 15 else if(*p==‘*‘) 16 { 17 p++; 18 afterStarPositionP=p; 19 afterStarPositionS=s; 20 } 21 else 22 { 23 if(afterStarPositionP!=NULL) 24 { 25 afterStarPositionS++; 26 s=afterStarPositionS; 27 p=afterStarPositionP; 28 } 29 else 30 { 31 return false; 32 } 33 } 34 } 35 36 while(*p==‘*‘) 37 { 38 p++; 39 } 40 41 if(*p==‘\0‘) return true; 42 else return false; 43 } 44 };
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4215722.html