您的位置:首页 > 其它

LeetCode之10 --- Regular Expression Matching

2016-04-07 20:22 369 查看

题目:

  ,

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


题目大意:

  实现正则表达式的*和.符号,要求输入两个字符串,第一个为原串,第二个为匹配串。返回成功或失败

思路:

  拿到题之后想到第一个思路就是进行暴力匹配,一个字符一个字符的进行匹配,一旦发现匹配成功就返回。此思路明显有缺陷,第一个缺陷是*前的有可能出现多次有可能一次都不出现,而上述简单匹配明显只能进行单一匹配。
  改进思路,对*前的字符在原串中用循环匹配完所有和这个相同的字符,然后再对不带*的一个一个进行匹配。上述思路在提交的时候爆出一个BUG,就是当余姚"aaa" "a*a"这种情况时在第一个*前的a就把原串中的所有a都匹配完了,导致返回了false的结果。对此思路的改进就是要在继续匹配时先对后边的串进行预处理,所以就有了下边这个思路(此代码参考学长博客:http://blog.csdn.net/wwh578867817/article/details/46128599

代码:

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;
}
}

}


PS:此题好难。。。。好心塞~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: