您的位置:首页 > 其它

Regular Expression Matching

2014-10-13 01:57 211 查看
'.' 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


这个和正常的re定义不一样, *按照题目里讲的是算前面字母的个数。递归的话,一般情况下

1. 考虑p[i+1] 是否为*

如果不是, 那就判断当前是否相等,且下一位时候match.

如果是, 则判断两种情况:

a. 把所有和p[i]能match的情况遍历,如果当前不match,那么继续下一个pattern.

    b. 如果都不能,那么放弃pi[i], 因为*可以为0

class Solution {
public:
bool isMatch(const char *s, const char *p) {
if (!s || !p)
return false;
if (*p=='\0')
return *s==*p;
if (*(p+1)=='*'){
while((*s==*p ||*s && *p=='.')){
if (isMatch(s,p+2))
return true;
s++;
}
return isMatch(s,p+2);
} else
return ((*s==*p || (*s!='\0' && *p=='.')) && isMatch(s+1,p+1));
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode