Implement wildcard pattern matching with support for '?'
and '*'
.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
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", "*") ? true
isMatch("aa", "a*") ? true
isMatch("ab", "?*") ? true
isMatch("aab", "c*a*b") ? false
// DFS超时
bool MatchDFS(const char *s, const char *p)
{
if (!(*s) && !(*p))
{
return true;
}
if (*s && !(*p))
{
return false;
}
if (!(*s) && *p)
{
while (*p)
{
if (*p != '*')
return false;
++p;
}
return true;
}
char ch1 = *s;
char ch2 = *p;
if (ch1 == ch2 || ch2 == '?')
{ // 疑问:如果ch1也为*,ch2也为*呢?
return MatchDFS(s + 1, p + 1);
}
if (ch2 == '*')
{
int i = 0;
while (*(s + i))
{// 匹配i个
if (MatchDFS(s + i, p + 1))
{
return true;
}
++i;
}
// 全部匹配
if (MatchDFS(s + i, p + 1))
return true;
}
return false;
}
bool isMatch(const char *s, const char *p)
{
return MatchDFS(s, p);
}
bool isMatch2(const char *s, const char *p)
{
int len1 = strlen(p);
int len2 = strlen(s);
if (len2 > 10000)
return false;
if (len1 == 0 && len2 == 0)
return true;
bool **f = new bool*[len1 + 1];
for (int i = 0; i <= len1; ++i)
{
f[i] = new bool[len2 + 1];
memset(f[i], 0, sizeof(bool) * (len2 + 1));
}
f[0][0] = true;
// 初始化
for (int i = 0; i < len1 && (*(p + i) == '*'); ++i)
{
f[i + 1][0] = true;
}
for (int i = 1; i <= len1; ++i)
{
for (int j = 1; j <= len2; ++j)
{
char ch1 = p[i-1];
char ch2 = s[j-1];
if (ch1 == ch2 || ch1 == '?')
{
if (f[i-1][j-1])
{
f[i][j] = true;
}
}
if (ch1 == '*')
{
for (int k = j; k >= 0; --k)
{
if (f[i-1][k])
{
f[i][j] = true;
break;
}
}
}
}
}
bool ans = f[len1][len2];
for (int i = 0; i <= len1; ++i)
{
delete[] f[i];
}
delete[] f;
return ans;
}
// 滚动数组
bool isMatch3(const char *s, const char *p)
{
int len1 = strlen(p);
int len2 = strlen(s);
if (len1 == 0 && len2 == 0)
return true;
bool **f = new bool*[2];
f[0] = new bool[len2 + 1];
memset(f[0], 0, sizeof(bool) * (len2 + 1));
f[1] = new bool[len2 + 1];
memset(f[1], 0, sizeof(bool) * (len2 + 1));
// f[0][0] = true;
// 初始化
for (int i = 0; i < len1 && (*(p + i) == '*'); ++i)
{
f[0][i] = true;
}
if (len2 == 0)
{
for (int i = 0; i < len1; ++i)
{
if (p[i] != '*')
return false;
}
return true;
}
int flag = 0;
for (int i = 1; i <= len1; ++i)
{
// 初始化
f[flag][0] = true;
for (int k = 0; k < (i - 1); ++k)
{
if (*(p + k) != '*')
{
f[flag][0] = false;
break;
}
}
for (int j = 1; j <= len2; ++j)
{
if (i == 1 && j == 1)
f[flag][0] = true;
char ch1 = p[i-1];
char ch2 = s[j-1];
if (ch1 == ch2 || ch1 == '?')
{
if (f[flag][j-1])
{
f[1-flag][j] = true;
}
}
if (ch1 == '*')
{
for (int k = j; k >= 0; --k)
{
if (f[flag][k])
{
f[1-flag][j] = true;
break;
}
}
}
}
memset(f[flag], 0, sizeof(bool) * (len2 + 1));
flag = 1 - flag;
}
bool ans = f[flag][len2];
delete[] f[0];
delete[] f[1];
delete[] f;
return ans;
}