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
The basic idea is to see if the string s and P's substring from I and J are matched, and the recursive method is used until the end of the string, and finally back to get the result. Assuming that we now go to the I position of S, P's J position, the situation is divided into the following two kinds:
(1) p[j+1] not ' * '. The situation is relatively simple, as long as the current S I and P J characters are the same (if there is a P on J character is '. ', is the same), if different, return false, otherwise, recursive next layer i+1,j+1;
(2) p[j+1] is ' * '. Then look at the substring starting from s[i], assuming that s[i],s[i+1],... s[i+k] are equal to p[j] then it means that these are likely to be suitable matches, then recursion for the remainder (i,j+2), (i+1,j+2),..., (i+k,j+2) to try (j +2 is due to skipping the current and next ' * ' characters).
The C + + implementation code is as follows:
#include <iostream>#include<string>using namespacestd;classSolution { Public: BOOLIsMatch (Const Char*s,Const Char*p) {returnHelperstring(s),string(p),0,0); } BOOLHelperConst stringSConst stringp,size_t i,size_t J) { if(j==p.length ())returni==s.length (); //P.charat (j+1)! = ' * ' if(J==p.length ()-1|| p[j+1]!='*') { if(I==s.length () | | (s[i]!=p[j]&&p[j]!='.')) return false; Else returnHelper (s,p,i+1, j+1); } //P.charat (j+1) = = ' * ' while(I<s.length () && (s[i]==p[j]| | p[j]=='.')) { if(Helper (s,p,i,j+2)) return true; I++; } returnHelper (s,p,i,j+2); }};intMain () {solution SS; Const Char*s="AA"; Const Char*p=". *BBB"; cout<<ss.ismatch (s,p) <<Endl;}
Regular Expression Matching