Implement regular expression matching with 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", "A *") →trueismatch ("AA", ". *") →trueismatch ("AB", ". *") →true IsMatch ("AaB", "C*a*b") →true
This problem beginners more or less refer to the online answer, the main difficulties have the following
First, to understand the meaning of the regular expression. and *, "." Represents any character, but "a *" stands for "", "a", "AA", "AAA" ... It's easier for a person to get confused.
Second, must be completely histograms, namely IsMatch ("AA", "AAA") →false
The first parameter, string s, does not contain "." and "*", so don't complicate the program
The Java implementation is as follows:
Static Public BooleanIsMatch (String s, String p) {//If you start with s length, s.length () = = 0 O'Clock ("", "*"), ("", "a*b*") will return True if(p.length () = = 0) returnS.length () = = 0; if(p.length () = = 1) returnS.length () = = 1 && (p.charat (0) = = '. ' | | S.charat (0) = = P.charat (0)); if(P.charat (1)! = ' * '){ if(s.length () = = 0 | | (P.charat (0)! = '. ' && s.charat (0)! = P.charat (0))) return false; returnIsMatch (s.substring (1), p.substring (1)); }Else { if(IsMatch (S, p.substring (2))) return true; Else{ intLen = S.length ();//Space Change Time inti = 0; while(I<len && (p.charat (0) = = '. ' | | P.charat (0) = =S.charat (i))) { if(IsMatch (S.substring (i+1), p.substring (2))) return true; I++; } } return false; } }
Java for Leetcode 010 Regular Expression Matching