Seek the Name, Seek the Fame POJ - 2752 (KMP 失配指针数组)

版权声明: https://blog.csdn.net/sgh666666/article/details/82427480

题意:

    给定一个串T,找出串T的子串,该串即既是T的前缀也是T的后缀.从小到大输出所有符合要求的子串的长度.

分析:
  把答案就是f[m]  f[ f[m] ]...依次下去.理解f数组的前缀后缀思想这道题就迎刃而解了.

 

#include<bits/stdc++.h>

using namespace std;

const int maxn = 1e7;
char t[maxn],p[maxn];

int f[maxn];
int n,m;

void getfail()
{
    f[0]=f[1]=0;
    for(int i=1;i<m;i++)
    {
        int j=f[i];
        while(j && p[i]!=p[j])j=f[j];
        f[i+1]=p[i]==p[j]?j+1:0;
    }
}

int  kmp()
{
    getfail();
    int j=0;
    for(int i=0;i<n;i++)
    {
        while(j && t[i]!=p[j])j=f[j];
        if(t[i]==p[j])j++;
        if(i==n-1)return j;
    }
}

int main()
{
    while(scanf("%s %s",p,t)!=EOF)
    {
        n=strlen(t);
        m=strlen(p);
        int tmp=kmp();
        if(tmp==0)
            puts("0");
        else
        {
            for(int i=0;i<tmp;i++)
                printf("%c",p[i]);
            printf(" %d\n",tmp);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/sgh666666/article/details/82427480
今日推荐