?理解不能

#include<cstdio>
#include<cstring>

using namespace std;

const int MAXN = 1e4 + 10;
char s[MAXN*100],str[MAXN];
int Next[MAXN];

void Get_KMP(int m)
{
    int i=0,j=-1;
    Next[0] = -1;
    while(i<m)
    {
        if(j==-1 || str[i] == str[j])
        {
            i++;j++;
            Next[i] = (str[i]!=str[j])?j:Next[j];
        }
        else 
        {
            j = Next[j];
        }
    }
}

int KMP(int n, int m)
{
    int j=0,i=0,ans=0;
    while(i<n)
    {
        if(j==-1 || s[i] == str[j])
        {
            i++;j++;
            if(j==m) 
            {
                ans++;
                i -= m - 1;
                j = 0;
            }
        }
        else 
        {
            j = Next[j];
        }
    }
    return ans;
}

int main()
{
    int t,ans;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s %s",str,s);
        int n = strlen(s);
        int m = strlen(str);
        Get_KMP(m);
        ans = KMP(n,m);
        printf("%d\n",ans);
    }
    return 0; 
}

猜你喜欢

转载自www.cnblogs.com/sdutzxr/p/12294258.html