通配符匹配(C语言实现)
实现
-
方法(1):递归实现
bool isMatch(const char *s, const char *p)
{
assert(s != NULL && p != NULL);
if(*p == '*')
{
while(*p=='*'){p++;}//跳出连续的*
if(*p == '\0'){return true;}
while(*s != '\0' && !isMatch(s,p)){s++;}
if(*s=='\0'){return false;}
else{return true;}
}
else if(*p == '\0' || *s == '\0')
{
return (*p==*s);
}
else if(*p==*s ||*p=='?')
{
return isMatch(++s,++p);
}
else {return false;}
}
-
方法(2):迭代实现
bool isMatch(const char *s, const char *p)
{
assert(s != NULL && p != NULL);
bool star=false;
const char *str=s;
const char *ptr=p;
while(*str!='\0')
{
switch(*ptr)
{
case '?': break;
case '*':
star=true;
s=str;
p=ptr;
while(*p=='*')
{
p++;
}
if(*p=='\0'){return true;}
str=s-1;
ptr=p-1;
break;
default:
if(*str!=*ptr)
{
if(!star)
{
return false;
}
s++;
str=s-1;
ptr=p-1;
}
}
str++;
ptr++;
}
while(*ptr == '*'){ptr++;}
return (*ptr == '\0');
}
-
方法(3):动态规划
bool isMatch(const char *s, const char *p)
{
assert(s != NULL && p != NULL);
int row=strlen(p);
int col=strlen(s);
int **arr=(int **)calloc(row+1,sizeof(int *));
for(int i=0;i<=row;i++)
{
arr[i]=(int *)calloc(col+1,sizeof(int));
}
arr[0][0]=1;
for(int i=1;i<=row;i++)
{
if(p[i-1]=='*')
{
arr[i][0]=arr[i-1][0];
}
}
for(int i=1;i<=row;i++)
{
for(int j=1;j<=col;j++)
{
if(p[i-1]=='*')
{
arr[i][j]=arr[i-1][j] || arr[i][j-1] || arr[i-1][j-1];
}
else
{
arr[i][j]=arr[i-1][j-1] && (p[i-1]==s[j-1] || p[i-1]=='?');
}
}
}
// for(int i=0;i<=row;i++)
// {
// for(int j=0;j<=col;j++)
// {
// printf("%d ",arr[i][j]);
// }
// printf("\n");
// }
return arr[row][col];
}
借鉴:以下几篇博客的分析
https://blog.youkuaiyun.com/a83610312/article/details/9750655
https://blog.youkuaiyun.com/glDemo/article/details/47678159
https://blog.youkuaiyun.com/Scarlett_Guan/article/details/80153099