Implement regular expression matching with support for ‘.‘
and ‘*‘
.
‘.‘ Matches any single character. ' * ' Matches zero or more of the preceding element. 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") →falseismatch ( "AA", "AA") →trueismatch ("AAA", "AA") →falseismatch ("AA", "A *") →trueismatch ("AA", ". *") →trueismatch ("AB", ". *") →true IsMatch ("AaB", "C*a*b") →true
Idea one: the idea of recursion.
Public BooleanIsMatch (String s, String p) {//p is empty if(P.isempty ())returnS.isempty (); //p The currently matched character is not followed by * if(p.length () = = 1 | | P.charat (1)! = ' * ') { //if the first character matches, each one character is gone backwards, otherwise it doesn't match if(Isfirstmatch (S, p))returnIsMatch (s.substring (1), p.substring (1)); Else return false; } //p Current matched character followed by *//when the first character matches, the first judgment is to remove the current P-matched x* (because it can be 0 x), such as AAA matching a*a//and then move s back one character to continue judging. while(Isfirstmatch (S, p)) {if(IsMatch (S, p.substring (2)))return true; S= s.substring (1); } //Skip x* To continue matching when the first character of S does not match returnIsMatch (S, p.substring (2)); }
IDEA two: Dynamic programming thought.
Public Booleanismatchii (String s, String p) {Boolean[] match =New Boolean[S.length () +1]; Arrays.fill (Match,false); //Match[j] matches for s[j~slen-1] and p[i~plen-1]Match[s.length ()] =true; for(intI=p.length () -1;i>=0;i--){ if(P.charat (i) = = ' * '){ for(intJ=s.length () -1;j>=0;j--) match[j] = match[j]| | match[j+1]&& (P.charat (i-1) = = '. ' | | S.charat (j) ==p.charat (i-1)); I--; } Else{ for(intJ=0;j<s.length (); j + +) Match[j] = match[j+1]&& (P.charat (i) = = '. ' | | P.charat (i) = =S.charat (j)); //TODO: This code doesn't know whyMatch[s.length ()] =false; } } returnMatch[0]; }
Regular Expression Matching