模板5:KMP

        char s2[10005];
        char s1[1000005];
        scanf("%s%s",s2,s1);
        int next[10005];
        int i=0,k=-1,j=0;
        next[0]=-1,next[1]=0;
        int len1=strlen(s1);
        int len2=strlen(s2);
        while(j<len2)
        {
            if(k==-1||s2[k]==s2[j])
            {
                j++;k++;
                if(s2[k]!=s2[j]) next[j]=k;
                else next[j]=next[k];
            }
            else k=next[k];
        }
        j=0;
        int ans=0;
        while(i<len1)
        {
            while(j!=-1&&s1[i]!=s2[j])
            {
                j=next[j];
            }
            i++;
            j++;
            if(j>=len2) {ans++;j=next[j];}
        }
        printf("%d\n",ans);

求s1串中s2串出现了几次

易更改为求s1串中是否包含s2

猜你喜欢

转载自blog.csdn.net/z26y25j10/article/details/82973420