One Day Together Leetcode series (i) Title
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
(ii) Problem solving
1. Recursive solution
The first thing you see in this question is the regular expression that you did before, the "one Day Leetcode" #10. Regular Expression Matching, so thought not to think, according to the previous method, it is obvious that the time-out.
/*1. If s[i]==p[j]| | P[J] = = '? ', then i++,j++2. if p[j] = = ' * ', Judge S[i] and P[j+1] after the string can match, if you can return true, if not i++*/classSolution { Public:BOOLIsMatch (stringSstringP) {inti =0;intj =0; while(I<s.length () &&j<p.length ()) {if(S[i] = = P[j] | | p[j] = ='? ') {i++; j + +; }Else if(P[j] = =' * ') {if(J==p.length ()-1)return true;Else{ while(I<s.length () &&s[i]!=p[j+1]) i++;if(I==s.length ())return false;Else{stringTmps = S.substr (I,s.length ());stringTmpp = P.substr (j+1, P.length ());if(IsMatch (TMPS,TMPP))return true;//Determine if the following can be matched Elsei++; } } }Else Break; }if(I==s.length () &&j==p.length ())return true;Else return false; }};
2. Backtracking method
First we look at an example CAABBBBC and c*ab*c, which can be written in c......ab.....c, so that we can match it by finding AB between two C.
So when it comes to *, record the Spre = i and ppre = ++j, then compare S[++i] and p[++j], if not the same time back to I=++spre,j=ppre,
If you touch the next ' * ', it means AB has finished matching, update spre and Ppre, and loop the comparison until the end of the string.
This is the main idea of the solution.
classSolution { Public:BOOLIsMatch (stringSstringP) {inti =0, j =0;intSlen = S.length ();intPlen = P.length ();intSpre =0, Ppre =0;//Backtracking method BOOLIsflag =false; while(I<slen) {if(S[i]==p[j] | | p[j]=='? ') {i++; j + +; }Else if(P[j] = =' * ') {ppre = ++j;//record * position, one-time backtracking matchSpre = i; Isflag =true;//Represent previous ' * '}Else{if(Isflag)//s[i]! = P[j] and p[j]! = '? ', Match failed, backtracking{i = ++spre; j = Ppre; }Else return false;//If there is no previous ' * ', then the match fails, returning false} } while(p[j]==' * ') j + +;//Prevent the occurrence of a special case where P is ' * ' at the end if(J==plen)return true;Else return false; }};
"One Day together Leetcode" #44. Wildcard Matching