class Solution {
public:
bool isMatch(const char *s, const char *p) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s == NULL || p == NULL)
{
return false;
}
bool match = true;
int i = 0, j = 0;
int lenS = strlen(s), lenP = strlen(p);
while( i <= lenS)
{
if (j >= lenP)
{
//模式串匹配结束(p串已耗尽),查看主串(s串)是否有剩余
match = i == lenS ? true : false;
break;
}
if (p[j + 1] == '*')
{
//若是'*',则分别按照'*'匹配0个、1个、...n个字符来试探
if (isMatch(s + i, p + j + 2))
{
return true;
}
while (i < lenS && isCharMatch(s[i], p[j]))
{
if (isMatch(s + i + 1, p + j + 2))
{
return true;
}
++i;
}
//能运行到这里,说明无论'*'匹配多少个字符,都不满足整体的正则匹配
return false;
}
else
{
//不是'*',必须匹配一个
if (i < lenS && isCharMatch(s[i], p[j]))
{
++i;
++j;
}
else
{
match = false;
break;
}
}
}
match = j == lenP ? match : false;
return match;
}
bool isCharMatch(char c, char p)
{
return c == p || p == '.';
}
};
LeetCode-Regular Expression Matching
最新推荐文章于 2024-07-25 18:22:10 发布