Regular Expression Matching
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
Problem Solving Ideas:
Test instructions to implement a regular expression match. which supports. and *
Divided into three different situations. The subscript for the current string and pattern is i,j, respectively.
1, if the current pattern is complete, that is, p[j]== ' ", if the end of the string, then return True, otherwise return false
2, if the next character of the pattern is not *, that is p[j+1]!= ' * '. Here is a discussion of the situation.
(1) If S[I]==P[J], recursive verification i+1, j+1
(2) if p[i]== '. ' and s[i]!= ' + ', recursive verification i+1, j+1
(3) Otherwise, return false
3, if the next character of the pattern is *, that is, p[j+1]== ' * ', then continuously through the recursive backtracking i+k,j+2 (k from 0 to Len (s)-i,j+2 means to cross the current character and *).
The code is as follows:
Class Solution {public: bool IsMatch (string s, String p) { return matchhelper (S, p, 0, 0); } BOOL Matchhelper (string& S, string& p, int i, int j) { if (p[j]== ') } {return s[i]== '; } if (p[j + 1]! = ' * ') { return (s[i] = = P[j]) | | (P[j] = = '. ' && s[i]!= ') ") && Matchhelper (S, p, i + 1, j + 1); } while ((s[i] = = P[j]) | | (P[j] = = '. ' && s[i]!= ') ") { if (Matchhelper (S, p, I, j+2)) return true; i++; } Return Matchhelper (S, p, I, j+2); }};
[Leetcode] Regular Expression Matching