‘?‘ 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
Idea: The solution of using dynamic dynamic programming
Set DP[I][J] to indicate whether S[0,i] and p[0,j] match;
The code is as follows: This method runs memory overflow
Public BooleanIsMatch (String s, String p) {if(s! =NULL&& P! =NULL&&s.equals (p))return true; if(". Equals (s) | |" ". Equals (p))return false; intn =s.length (); intm =p.length (); Boolean[] DP =New Boolean[N][m]; if(S.charat (0) = = P.charat (0) | | P.charat (0) = = '? ' | | P.charat (0) = = ' * ') dp[0][0] =true; Else return false; for(inti=0; i<n; i++) { for(intj=0; j<m; J + +) { if(i = = 0 && J > 0) { if(P.charat (j) = = ' * ') Dp[i][j]= Dp[i][j-1]; ElseDp[i][j]=false; }Else if(i > 0 && j = = 0) { if(P.charat (j) = = ' * ') Dp[i][j]=true; ElseDp[i][j]=false; } Else if(I>0 && j>0){ if(P.charat (j) = = ' * ') {Dp[i][j]= (Dp[i-1][j] | | dp[i][j-1]); } Else if(P.charat (j) = = '? ' | | S.charat (i) = =P.charat (j)) {Dp[i][j]= Dp[i-1][j-1]; } Else { return false; } } } } returnDp[n-1][m-1]; }
Use a loop to traverse two strings, the code is as follows
Public BooleanIsMatch (String s, String p) {if("*". Equals (p))return true; intPosS = 0; intPosP = 0; intPOSG =-1;//The location of a recent "*" intPossnext =-1; while(PosS <s.length ()) { if(Posp<p.length () && p.charat (posP) = = ' * ') {POSG=PosP; PosP++; Possnext= PosS + 1; } Else if(Posp<p.length () && (S.charat (posS) = = P.charat (PosP) | | P.charat (posP) = = '? ') ) {PosS++; PosP++; } Else if(POSG = =-1){ return false; } Else{PosP= Posg+1; PosS=Possnext; Possnext++; } } while(PosP < P.length () && p.charat (posP) = = ' * ') PosP++; if(PosP >=p.length ())return true; return false; }
LeetCode-44 Wildcard Matching