HDU4763 Theme Section KMP

HDU4763 Theme Section KMP

/*KMP字符串匹配 next[i]记录1~i中相同前后缀长度-1 即相同字符下标位置
234MS	6416K
*/
#include <stdio.h>
#include <string.h>
const int MAX=1e6+5;
char str[MAX];
int next[MAX];
void buildnext(char *str2,int m)//建立next数组
{
    next[0]=-1;
    for (int k=1,i=-1;k<m;k++)
    {
        while (str2[i+1]!=str2[k]&&i!=-1) i=next[i];
        if (str2[i+1]==str2[k]) i++;
        next[k]=i;
    }
}
int main ()
{

    int T;
    scanf ("%d",&T);
    getchar();
    while (T--)
    {
        memset(next,0,sizeof(next));
        int k=-1,i,ans=0;
        char a;
        while (a=getchar())
        {
            if (a=='\n') break;
            str[++k]=a;
        }
        buildnext(str,k+1);
        for (i=next[k];i>=0&&ans==0;i--)
        {
            for (int j=1;j<k&&ans==0;j++)
                if (next[j]>=i)
                    ans=i+1;
        }
        printf ("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/nrtostp/article/details/80160155