您的位置:首页 > 其它

LeetCode:Regular Expression Matching

2014-06-18 13:27 393 查看
思路:借助网上的discuss,发现对于模式串,以下一个字符是否为 "*"来分开讨论,假设两个字符串a,b,如果*(b+1)是'*'那么需要多个字符*a匹配*b,如果没有匹配*b的,根据'*'的意思,递归比较a,b+2两个字符串即可,此时 '*' 匹配0个字符串。如果*(b+1)不是'*',那么当前的*a和*b必须要匹配,或者*a == *b,或者*b = '.' 。

注意:'*'表示字符串中的字符,即通配符,而*a,*b表示解引用,表示a、b所指地址存储的字符。

code:

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