Problem Description:
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:
Starting with the position of the string s and P sp,pp, and using recursive method to reduce the length of the string, and finally back to the comparison results.
Suppose now go to the SP,PP place respectively. is divided into the following situations:
(1) If the position of the PP has crossed, then if the SP has crossed, then return true; otherwise the S string has a length, does not match, returns false;
(2) The position of PP is the last of P, then only one by one matches, if the mismatch returns false; otherwise the next comparison;
(3) pp position compared to the front, then compare pp next. If the next one is not ' * ', then only one by one matches, or false if not matched, otherwise the next comparison. If the next one is ' * ', the position of the PP is moved backwards by two bits, and the SP's position is now a brute force comparison, one for each move backwards.
The code is as follows:
1 Public classSolution {2 Public Static BooleanIsMatch (String s, String p) {3 if(s = =NULL)4 returnp = =NULL;5 if(p = =NULL)6 returns = =NULL;7 returnHelper (s, p, 0, 0);8 }9 Private Static BooleanHelper (string s, String p,intSpintPP) {Ten if(pp >=p.length ()) One returnSP >=s.length (); A //pp comes to end - if(pp = = P.length ()-1) { - if(SP >=s.length () the|| (S.charat (sp)! = P.charat (PP) && p.charat (PP)! = '. ')) - return false; - Else - returnHelper (S, p, SP + 1, pp + 1); + } - //P.charat (pp+1)! = ' * ' + if(P.charat (pp + 1)! = ' * ') { A if(SP >=s.length () at|| (S.charat (sp)! = P.charat (PP) && p.charat (PP)! = '. ')) - return false; - Else - returnHelper (S, p, SP + 1, pp + 1); - } - //P.charat (pp+1) = = ' * ' in while(SP <s.length () -&& (P.charat (pp) = = '. ' | | s.charat (SP) = =P.charat (PP))) { to if(Helper (S, p, SP, pp + 2)) + return true; -sp++; the } * returnHelper (S, p, SP, pp + 2); $ }Panax Notoginseng}
Java [Leetcode] Regular Expression Matching