Mplement wildcard pattern matching with the 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") →falseismatch ( "AA", "AA") →trueismatch ("AAA", "AA") →falseismatch ("AA", "*") →trueismatch ("AA", "A *") →trueismatch ("AB", "? *") →truei Smatch ("AaB", "C*a*b") →false
The question is the matching problem, if encountered '? ' Match any one character, if it's ' * ', match 0-n characters. The greedy algorithm is used to solve. Time: 20ms. The code is as follows:
classSolution { Public: BOOLIsMatch (stringSstringp) {if(P.empty ())returnS.empty (); string:: Const_iterator pter = P.begin (), ster =S.begin (); string:: Const_iterator star_p, star_s; BOOLSign =false; while(ster!=S.end ()) { if(Pter = =P.end ()) { if(sign) {ster= ++star_s; Pter=star_p; } Else Break; } Else if(*pter = ='?'|| *pter = = *ster)++pter, + +ster; Else if(*pter = ='*'){ while(Pter! = P.end () && (*pter = ='*'|| *pter = ='?')){ if(*pter = ='?'){ ++Pter; ++ster; if(Ster = =s.end ()) Break; } Else++Pter; } if(pter==p.end ())return true; Star_p=Pter; star_s=ster; Sign=true; } Else if((*pter! = *ster | | *pter!='?') &&Sign ) {Ster= ++star_s; Pter=star_p; } Else return false; } if(Ster! =s.end ())return false; while(pter!=p.end ())if(*pter++! ='*') return false; return true; }};
[Leetcode] #44 Wildcard Matching