OpenJudge 带通配符的字符串匹配

 6252:带通配符的字符串匹配

描述

通配符是一类键盘字符,当我们不知道真正字符或者不想键入完整名字时,常常使用通配符代替一个或多个真正字符。通配符有问号(?)和星号(*)等,其中,“?”可以代替一个字符,而“*”可以代替零个或多个字符。 

你的任务是,给出一个带有通配符的字符串和一个不带通配符的字符串,判断他们是否能够匹配。 

例如,1?456 可以匹配 12456、13456、1a456,但是却不能够匹配23456、1aa456; 
2*77?8可以匹配 24457798、237708、27798。

输入

输入有两行,每行为一个不超过20个字符的字符串,第一行带通配符,第二行不带通配符

输出

如果两者可以匹配,就输出“matched”,否则输出“not matched”

样例输入

1*456?
11111114567

样例输出

matched

 模拟字符串匹配的过程,注意下面几个测试样例

123*45*6
1237894523454336
*?
123456
2*77?8
24457798

以下就是满分的AC代码: 

#include <stdio.h>
#include <string.h>
char str1[21];
char str2[21];
char temp[21];

char* mystrstr(char* s1,char* s2)
{
    int i,j;
    int len1=strlen(s1);
    int len2=strlen(s2);
    for(i=0;i<len1;i++)
    {
        for(j=0;j<len2&&i<len1;)
        {
            if(s1[i]==s2[j])
            {
                i++;
                j++;
            }
            else if(s2[j]=='?')
            {
                i++;
                j++;
            }
            else break;
        }
        if(j==len2)
        {
            return (s1+i-len2);
        }
    }
    return NULL;
}

int main()
{
    scanf("%s %s",str1,str2);
    int len1=strlen(str1);
    int len2=strlen(str2);
    int i=0;
    int j=0;
    int flag=1;
    while(i<len1&&j<len2)
    {
        if(str1[i]=='*')
        {
            int cnt=0;
            int p1=(++i);
            if(i==len1)
            {
                j=len2;
            }
            else
            {
                int p2=0;
                while(str1[p1]!='*'&&str1[p1]!='\0')
                {
                    temp[p2++]=str1[p1++];
                }
                temp[p2]='\0';
                char* p3=str2+j;
                while(mystrstr(p3,temp))
                {
                    p3=mystrstr(p3,temp);
                    p3+=strlen(temp);
                }
                j=(p3-str2);
                i+=strlen(temp);
            }
        }
        else if(str1[i]=='?')
        {
            i++;
            j++;
        }
        else{
            if(str1[i]==str2[j])
            {
                i++;
                j++;
            }
            else
            {
                flag=0;
                break;
            }
        }
    }
    while(i<len1)
    {
        if(str1[i]=='*') i++;
        else
        {
            flag=0;
            break;
        }
    }
    if(i==len1&&j==len2&&flag) printf("matched\n");
    else printf("not matched\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/chengsilin666/article/details/82564369