您的位置:首页 > 其它

LeetCode算法题目: Regular Expression Matching

2017-04-05 18:14 323 查看

题目:

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

分析:

场景1:a*ab “aaab”

场景2:abac “ac”

用递归的方法来处理,对于x*,要处理有0到N个x被match下后剩下的递归匹配。

对于其他非x*的场景,直接匹配之后递归即可。

注意:当匹配串全部完成之后,如果模式串还有,查看一下剩下的模式串是不是可以匹配空字符串的即可,比如“abc*”的任意重复pair形式。

代码:

bool isMatch(const char *s, const char *p) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (*p == 0) return *s == 0;
if (*(p+1) != '*')
{
if (*s != 0 && (*p == *s || *p == '.')) return isMatch(s+1, p+1);
else return false;
}
else
{
// *s == *p
while (*s != 0 && (*s == *p || *p == '.'))
{
if (isMatch(s, p+2)) return true;
s++;
}
return (isMatch(s, p+2));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode