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
Positioning: Difficult questions
The topic gives two matching rules, ie '. ' Can match any character, ' * ' can repeat the previous character 0 to any time.
At this point we will ' * ' conform to the previous word as a unit consideration. The following conditions exist:
- Two string lengths are 0 and return true;
- The previous length is 0, and the latter one contains the ' * ' element, which returns true;
- Take the preceding preceding character and the preceding paragraph, if the previous preceding paragraph is a repeating character, take to the non-repeating position, the next one to determine if there is a ' * ' unit to match, matching correct removal of the matched part will be the rest of the recursive, the mismatch returns false.
Java implementations:
1 Public classSolution {2 Public BooleanIsMatch (String s, String p) {3 if(P.length () ==0){4 returnS.length () ==0;5 }6 Else if(S.length () ==0) {7 if(P.length () >1&&p.charat (1) = = ' * ')returnIsMatch (S, p.substring (2));8 Else return false;9}Else if(P.length () >1 && p.charat (1) = = ' * ') {Ten if(IsMatch (S,p.substring (2)))return true; One Else if(S.charat (0) ==p.charat (0) | | P.charat (0) = = '. ') { A returnIsMatch (s.substring (1), p); -}Else return false; -}Else { the return(S.charat (0) ==p.charat (0) | | P.charat (0) = = '. ') && IsMatch (s.substring (1), p.substring (1)); - } - } -}
Leetcode 010 Regular Expression Matching-java