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") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
int isMatch(char *s, char *p) { //递归出口判断 if (p[0] == '\0') { return s[0] == '\0'; } //分状况解决匹配问题,一种带*一种不带* if (p[1] == '*') { //带* while (s[0] != '\0' && (p[0] == '.' || s[0] == p[0])) { //若是匹配成功 if (isMatch(s, p + 2)) { //先把带*的匹配掠过,对后边的进行匹配 return 1; } ++s; //把s向后移动一位,而后再次匹配*前的元素(由于*前的元素可能出现屡次) } return isMatch(s, p + 2); //继续匹配剩下的 } else { //不带* //若是匹配成功 if (s[0] != '\0' && (p[0] == '.' || s[0] == p[0])) { return isMatch(s + 1, p + 1); //递归下一个元素匹配 } else { //没有匹配成功 return 0; } } }