http://acm.hdu.edu.cn/showproblem.php?pid=3901
Wildcard
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 125536/65536 K (Java/Others)
Total Submission(s): 424 Accepted Submission(s): 127
Problem Description
When specifying file names (or paths) in DOS, Microsoft Windows and Unix-like operating systems, the asterisk character (“*") substitutes for any zero or more characters, and the question mark (“?") substitutes for any one character.
Now give you a text and a pattern, you should judge whether the pattern matches the text or not.
Now give you a text and a pattern, you should judge whether the pattern matches the text or not.
Input
There are several cases. For each case, only two lines. The first line contains a text, which contains only lower letters. The last line contains a pattern, which consists of lower letters and the two wildcards (“*", "?").
The text is a non-empty string and its size is less than 100,000, so do the pattern.
The text is a non-empty string and its size is less than 100,000, so do the pattern.
Output
Output “YES” if the pattern matches the text, otherwise “NO”.
Sample Input
abcdef
a*c*f
a*c*f
Sample Output
YES
题意:含通配符'*'和'?'的模式匹配,问你两个串是否相等。
分析:本题的模式可以表示为S1*S2*…*Sn-1*Sn ,其中Si 只由小写字母和’?’组成。
首先检查S1,Sn 是否匹配文本,然后得到的模式变成*S2*…*Sn-1*的形式。这
种形式首尾都含有‘*’。然后可以贪心的检查S2 … Sn-1 这些片段是否依次出现
在文本中,需要使用kmp。若模式串长度为M,文本串长度为N,则此题的时间
复杂度为O(M + N)。
很多细节需要注意
代码:
#include<stdio.h>
#include<string.h>
#define N 100050
char str[N],s[N],temp[N];
int next[N],nn,mm,jj;
void Next(char *word)
{
int n,k=-1,j=0;
next[0]=-1;
n=strlen(word);
while(j<n)
{
if(k==-1||word[j]==word[k]||word[j]=='?'||word[k]=='?')
{
j++;k++;
next[j]=k;
}
else
k=next[k];
}
}
int match(char *word,int &i)
{
int j=0;
int m=strlen(word);
while(i<=jj&&j<m)
{
if(j==-1||s[i]==word[j]||word[j]=='?')
i++,j++;
else
j=next[j];
}
if(j>=m)
return 1;
return 0;
}
int main()
{
int n,i,j,ii,flag,m;
while(scanf("%s",s)!=EOF)
{
n=strlen(s);
scanf("%s",str);
m=strlen(str);
for(i=0;i<m;i++)
if(str[i]=='*')
break;
if(i>=m)
{
i=0;j=0;
while(n==m&&i<n&&j<m)
if(s[i]!=str[j]&&str[j]!='?')
break;
else i++,j++;
if(j>=m)
printf("YES\n");
else
printf("NO\n");
continue;
}
i=0;j=0;flag=0;
while(i<n&&j<m&&str[j]!='*')
if(s[i]!=str[j]&&str[j]!='?')
{
flag=1;
break;
}
else i++,j++;
if(flag)
{
printf("NO\n");
continue;
}
nn=j;ii=i;
i=n-1;j=m-1;flag=0;
while(i>=0&&j>=0&&str[j]!='*')
if(s[i]!=str[j]&&str[j]!='?')
{
flag=1;
break;
}
else i--,j--;
if(flag)
{
printf("NO\n");
continue;
}
mm=j;jj=i;
i=nn;
if(ii-jj>1)
{
printf("NO\n");
continue;
}
while(i<=mm)
{
while(i<=mm&&str[i]=='*')
i++;
j=0;
while(i<=mm&&str[i]!='*')
{
temp[j++]=str[i];
i++;
}
if(j>0)
{
temp[j]=0;
memset(next,-1,sizeof(next));
Next(temp);
if(!match(temp,ii))
{
flag=1;break;
}
}
}
if(flag)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}