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
class Solution { public: bool isMatch(const char *s, const char *p) { //此方法是网上的一个比较简单的方法,原理与下面的方法差不多,没通过,不想研究了,以后研究吧 /* if (*p == '\0') return *s == '\0'; if (*(p + 1) != '*') { return ((*p == *s) || (*p == '.' && *s != '\0')) && isMatch(s + 1, p + 1); } while ((*p == *s) || (*p == '.' && *s == '\0')) { if (isMatch(s, p + 2)) return true; s++; } return isMatch(s, p + 2); */ } /*bool isMatch(const char *s, const char *p) { //刚开始题目有些理解错误,把'*'理解为匹配任意并任意多的字符,在此题中是匹配任意多的前缀字符,注意题目意思,个人感觉此方法不是最优的,存在重复计算,更优的解留给以后 int len1 = strlen(s), len2 = strlen(p); return ismatch(s, p, 0, 0, len1, len2); } bool ismatch(const char *s, const char *p, int index1, int index2, int length1, int length2) { int i = index1, j = index2; while (i < length1 && j < length2) { //首先我把p[j]分为两种情况,一种是后面带'*', 一种是独立的字母的 if (j + 1 < length2 && p[j+1] == '*') { if (ismatch(s, p, i, j + 2, length1, length2) == false) { if (s[i] == p[j] || p[j] == '.') ++i; else return false; } else return true; } else { if (s[i] == p[j] || p[j] == '.') { ++i; ++j; } else return false; } } while (j + 1 < length2 && p[j + 1] == '*') j += 2; if (i == length1 && j == length2) return true; else return false; }*/ };