Describe
Implement wildcard Paern 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
Analysis
It's very similar to the previous question.
The main problem is ' * ' matching. P each encounter a ' * ', will retain the current ' * ' coordinates and s coordinates, and then s in the past
Scan backwards, if unsuccessful, s++, rescan
Code
1 Public classWildcardmatch {2 3 Public Static voidMain (string[] args) {4 //TODO auto-generated Method Stu5String s= "AaB";6String p= "*";7 System.out.println (IsMatch (s,p));8 }9 //RecursiveTen Public Static BooleanIsMatch (String s, String p) { One if(p.length () = = 0) A returnS.length () = = 0; - - if(P.charat (0) = = ' * ') { the - while(p!=NULL&&p.startswith ("*")) { - -P=p.substring (1);//Skip * + } - if(p==NULL) + return true; A while(s!=NULL&&!IsMatch (S, p)) atS=s.substring (1); - returns! =NULL; - } - - Else if(P.charat (0) = = ' + ' | | S.charat (0) = = ' + ')returnP.charat (0) = = S.charat (0); - Else if(P.charat (0) = = S.charat (0) | | P.charat (0) = = '? ') { in - returnIsMatch (s.substring (1), p.substring (1)); to } + Else return false; - }
the //Iteration Version * Public Static BooleanIsMatch2 (String s, String p) { $ inti = 0; Panax Notoginseng intj = 0; - intStar =-1; the intMark =-1; + while(I <s.length ()) { A if(J <p.length () the&& (P.charat (j) = = '? ' | | P.charat (j) = =S.charat (i))) { +++i; -++J; $}Else if(J < P.length () && P.charat (j) = = ' * ') { $Star = j + +; -Mark =i; -}Else if(Star! =-1) { thej = Star + 1; -i = + +Mark; Wuyi}Else { the return false; - } Wu } - while(J < P.length () && P.charat (j) = = ' * ') { About++J; $ } - returnj = =p.length (); - } -}
Wildcard Matching Leetcode Java