[LeetCode] Regular Expression Matching
Regular Expression Matching
Implement regular expression matching with support'.'
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", ".*") → trueisMatch("aab", "c*a*b") → true
Solution:
The question is to implement regular expression matching. Supported. And *
There are three cases. Set the subscript of the current string and mode to I, j, respectively.
1. If the current mode is matched, p [j] = '\ 0'. If the string ends, true is returned; otherwise, false is returned.
2. If the next character in the mode is not *, p [j + 1]! = '*'. We will discuss the situation here.
(1) If s [I] = p [j], recursive verification of I + 1, j + 1
(2) If p [I] = '.' And s [I]! = '\ 0', recursive verification I + 1, j + 1
(3) Otherwise, false is returned.
3. If the next character of the mode is *, that is, p [j + 1] = '*', Recursive Backtracking is performed continuously, j + 2 (k increases from 0 to len (s)-I, j + 2 means crossing 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]=='\0'){ return s[i]=='\0'; } if( p[j + 1] != '*'){ return ((s[i] == p[j]) || (p[j] == '.' && s[i]!='\0')) && matchHelper(s, p, i + 1, j + 1); } while((s[i] == p[j]) || (p[j] == '.' && s[i]!='\0')){ if(matchHelper(s, p, i, j+2)) return true; i++; } return matchHelper(s, p, i, j+2); }};