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 problem of matching the regular expression and the word Wildcard Matching wildcard match is very similar, the difference is that the meaning of the * is different, in the previous question, * means can replace any number of characters, and this problem * indicates that the previous character can have 1 or more, that is, the string a *b, can represent B or Aaab, that is, a number of arbitrary, the difficulty of the problem to be relative to before that a larger, sub-situation to be more complex, need to use recursive recursion to solve, the approximate idea is as follows:
-if p is empty, if s is also null, returns True, and vice versa returns false
-If the length of P is 1, if s length is also 1, and the same or P is '. ' Returns true, and vice versa returns false
-If the second character of P is not *, if S is null to return FALSE, then the first character is judged to match, and the recursive function match is called from the second character of each
-If the second character of P is *, if s is not empty and the character matches, call the recursive function to match s and remove the first two characters of P, if match returns true, otherwise s remove the first letter
-Returns the result of calling the recursive function to match s and removing the first two characters of P
classSolution { Public: BOOLIsMatch (stringSstringp) {if(P.empty ())returnS.empty (); if(p.size () = =1) { return(s.size () = =1&& (s[0] = = p[0] || p[0] =='.')); } if(p[1] !='*') { if(S.empty ())return false; return(s[0] = = p[0] || p[0] =='.') && IsMatch (S.substr (1), P.substr (1)); } while(!s.empty () && (s[0] = = p[0] || p[0] =='.')) { if(IsMatch (S, P.substr (2)))return true; S= S.substr (1); } returnIsMatch (S, P.substr (2)); }};
This topic also can be used to dynamically plan dynamic programming solution, in particular, see the Netizen Code ganker blog.
[Leetcode] Regular expression Matching regex match