Recursion may cause exceed time limited.
class Solution {
public:
bool isMatch(const char *s, const char *p) {
if (*p == '*'){//return true;
while(*p == '*') ++p;
if (*p == '\0') return true;
while(*s != '\0' && !isMatch(s,p)){
++s;
}
return *s != '\0';
}
else if (*p == '\0' || *s == '\0') return *p == *s;
else if (*p == *s || *p == '?') return isMatch(++s,++p);
else return false;
}
};But iteration can pass all the tests.class Solution {
public:
bool isMatch(const char *s, const char *p) {
if(!s && !p) return true;
const char *star_p=NULL,*star_s=NULL;
while(*s)
{
if(*p == '?' || *p == *s)
{
++p,++s;
}else if(*p == '*') {
while(*p == '*') ++p; //skip all continuous '*'
if(!*p) return true; //if end with '*', its match.
star_p = p; //store '*' pos for string and pattern
star_s = s;
}else if((!*p || *p != *s) && star_p) {
s = ++star_s; //skip non-match char of string, regard it matched in '*'
p = star_p; //pattern backtrace to later char of '*'
}else
return false;
}
while(*p) //check if later part of p are all '*'
if(*p++ != '*') return false;
return true;
}
};
本文探讨了使用递归和迭代两种方法实现字符串与模式之间的正则表达式匹配。通过对比发现递归方法可能导致时间限制超出,而迭代法则能顺利通过所有测试案例。文章详细解释了迭代法的实现思路与具体代码。
1375

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



