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