leetcode#44 Wildcard Matching

Source: Internet
Author: User

Original title Address

A very technical problem, although the essence is still search + backtracking, but the key is how to deal with the redundant in the pattern String *, if the bad processing time out.

The basic search + backtracking algorithm is this, for the original string s and the pattern string p, sequentially traversing its characters:

(a) if p[j]= "*", turn p[j+1..p.length] and s[i. S.length], S[i+1..s.length], S[i+2..s.length] ... Match, if all fails, I and J are traced back to the previous "*" position

(b) If s[i]= "?" or S[i]=p[j], indicating the current character match, at which point i++,j++

(c) Otherwise, indicates that the current character does not match, backtracking to the first asterisk position

It can be seen that if "*" a lot, and always fail, then the backtracking cost of the algorithm is huge

The optimization is: for Case (a), if the current match fails, the entire match fails, and you do not need to backtrack to the first asterisk.

To be blunt, it goes back to the last "*" of the P-string, and the forward "*" is out of control.

For example:

   
S:a b c D a C c c
| | \ \ \ \
P:a b * C d * A C C
|
Mismatch

In the example above, s[5]!=p[6], it is only necessary to backtrack to the second asterisk position (p[5]= "*"), without having to backtrack to the first asterisk position (p[2]= "*"). Because backtracking to an earlier "*" does not produce new matching results. (This conclusion has a chance to prove it later)

Code:

1 BOOLIsMatch (Const Char*s,Const Char*p) {2   Const Char*star =NULL;3   Const Char*backup =NULL;4         5    while(*s) {6     if(*p = ='*') {7Backup =s;8Star = + +p;9     }Ten     Else if(*p = ='?'|| *p = = *s) { Ones++; Ap++; -     } -     Else if(Star) { thep =Star; -s = + +backup; -     } -     Else +        Break; -   } +          A    while(*p = ='*') atp++; -   return!*s &&!*p; -}

leetcode#44 Wildcard Matching

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.