Implement wildcard pattern matching with the support for and ‘?‘
‘*‘
.
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
Problem solving idea One:
Referring to the previously written http://www.cnblogs.com/tonyluis/p/4464059.html, it is easy to write the code recursively, and the Java implementation is as follows:
Static public Boolean IsMatch (string s, String p) {if (s.length () ==0) {for (int i=0;i<p.length (); i++) if (P.charat (i)! = ' * ') return False;return true; if (p.length () = = 0) return s.length () = = 0; else if (p.length () = = 1) return P.charat (0) = = ' * ' | | (s.length () = = 1&& (P.charat (0) = = '? ' | | S.charat (0) = = P.charat (0))); if (P.charat (0)! = ' * ') { if (P.charat (0)!=s.charat (0) &&p.charat (0)! = '? ') return false; Return IsMatch (s.substring (1), p.substring (1)); } int index=0; while (Index<p.length ()) { if (P.charat (index) = = ' * ') index++; else break; } if (Index==p.length ()) return true; P=p.substring (index); for (int i=0;i<s.length (); i++) { if (IsMatch (s.substring (i), p)) return true; return false;}
Result Time Limit exceeded! That is to say, this brute-force enumeration algorithm must not pass!
Two ways to solve problems:
Use two pointers indexs and indexp to traverse S and p, while using two pointers Starindex and sposition to record the last occurrence of the position in the traverse process and the corresponding INDEXP position, once s and P do not match, return to the position of Starindex, At the same time sposition+1, and then traverse, until the completion of the complete S, note the boundary conditions, Java implementation is as follows:
Static public Boolean IsMatch (string s, string p) {int indexs=0,indexp=0,starindex=-2,sposition=-2;while (indexs< S.length ()) {if (Starindex==p.length ()-1) Return true;if (Indexp>=p.length ()) {if (starindex<0) return false; Indexp=starindex+1;indexs=++sposition;} if (S.charat (indexs) ==p.charat (indexp) | | P.charat (indexp) = = '? ') {indexs++;indexp++;} else if (P.charat (indexp) = = ' * ') {Starindex=indexp++;sposition=indexs;} else if (starindex>=0) {indexp=starindex+1;indexs=++sposition;} else return false;} while (Indexp<p.length ()) {if (P.charat (indexp) = ' * ') return false;indexp++;} return true;}
Java for Leetcode 044 Wildcard Matching