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
Analysis: The problem can still be categorized as a detailed problem, although seemingly complex, but careful analysis found that the logic, or relatively easy to achieve. So encounter more complex problems, to carefully analyze the possible situation, and then classify the different situations, so as to achieve from complex to simple.
We first discuss the characters following the current first character in P. Assuming P points to the current character, then there are two possible characters for p+1, one is ' * ' and the other is not ' * ' (feeling like crap).
1. If p+1 is not ' * ', if *p = = *s or *p = = '. ' and *s! = ' \ ', then p+1, two strings after s+1 may match; otherwise, two strings do not match.
2. If the p+1 is ' * '. Here we can be divided into three kinds of situation discussion:
1) if *p! = *s, then we need to judge IsMatch (S, p+2), because ' * ' here means the number of characters p points to is 0.
2) If *p = = *s, then we need to consider ' * ' to represent one or more *p cases.
3) If *p = = '. ' && *s! = ', then we need to consider the case that ' * ' represents a character to ' * ' for all characters after *s.
With the above analysis, we can implement IsMatch in a recursive way, the code is as follows:
classSolution { Public: BOOLIsMatch (Const Char*s,Const Char*p) {if(*p = =' /')return(sb==' /'; if(* (p+1) !='*'){//If Next is not ' * ' if(*p = = *s | | *p = ='.'&& *s! =' /') returnIsMatch (s+1, p+1); Else return false; }Else{ while(*p = = *s | | *p = ='.'&& *s! =' /'){ if(IsMatch (s,p+2)) return true; S++; } returnIsMatch (S, p+2); } }};
Leetcode:regular Expression Matching