Topic:
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
Code:
classSolution { Public: BOOLIsMatch (stringSstringp) {//both S and P reach their ends if(P.empty ())returnS.empty (); //P ' s next is not * if(p[1]!='*' ) { return(s[0]==p[0] || (p[0]=='.'&&!s.empty ()) && Solution::ismatch (S.substr (1), P.substr (1)); } //P ' s next is * and Curr s match curr P inti =0; for(; s[i]==p[0] || (p[0]=='.'&& i<s.size ()); ++i) {if(Solution::ismatch (S.substr (i), P.substr (2)) )return true; } //P ' s next is * but Curr s not match Curr P returnSolution::ismatch (S.substr (i), P.substr (2)); }};
Tips
This code is leetcode on the latest interface, which is AC-capable.
The idea is somewhat complex: the main judgment is whether the next p is *, and the classification is discussed.
Although the code is AC, some doubts still exist:
1. p[1]!= ' * ' this statement will encounter P[1] does not exist (index out of bounds), the result returned on my Mac is nul, but OJ can pass.
2. P.SUBSTR (2) This statement also encounters the same problem as 1.
Although the OJ passed, there are also various border hazards. If the string index is out of bounds, it should raise undefined behavior, but I don't know why.
Use DP to do it again and see if the boundary conditions can be simplified.
"Regular Expression Matching" cpp