题目来源:https://leetcode.com/problems/regular-expression-matching/
Regular Expression Matching
‘.’匹配任意单个字符,‘*’匹配0个或多个前一字符。如果匹配整个串返回true。
例:
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
解决方案转载自:http://www.cnblogs.com/codingmylife/archive/2012/10/05/2712561.html
bool isMatch(const char *s, const char *p)
{
if (s == NULL || p == NULL) return false;
if (*p == '\0') return *s == '\0';
// ".*" matches "", so we can't check (*s == '\0') here.
if (*(p + 1) == '*')
{
// Here *p != '\0', so this condition equals with
// (*s != '\0' && (*p == '.' || *s == *p)).
while ((*s != '\0' && *p == '.') || *s == *p)
{
if (isMatch(s, p + 2)) return true;
++s;
}
return isMatch(s, p + 2);
}
else if ((*s != '\0' && *p == '.') || *s == *p)
{
return isMatch(s + 1, p + 1);
}
return false;
}
本文介绍了一种解决正则表达式匹配问题的递归算法。该算法能处理包含'.'和'*'的正则表达式,其中'.'可以匹配任意单个字符,而'*'可以匹配其前面的字符0次或多次。通过递归调用自身来判断是否能够完全匹配给定的字符串。
1516

被折叠的 条评论
为什么被折叠?



