Seek the Name, Seek the Fame(找名字,要成名)

poj 2752 

题目大意:前边的串和后边的串相同的字符的个数

解决:kmp的next值,代表前边有多少和从开头的字符串相同

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char str[400005];
int  next[400005];
int res[400005];
int main()
{
    while(scanf("%s",str+1)!=EOF)
    {
        int i=1,j=0,k=0;
        next[1]=0;
        int len=strlen(str+1);//改进了之后下边这个判断可以删去了,

         if(len==1){printf("%d\n",1); continue;}
        while(i<=len)
        {//这个地方关键是要求最后一个必须是求到i=len
            if(j==0 || str[i]==str[j])
            {
                i++;j++;
                next[i]=j;
            }
            else j=next[j];
        }
        res[k++]=len;
       //next[len+1]的值代表,字符串结束的位置前边有next[len+1]个字符串和从开头开始的字符串相同
      //下边的循环表示,前边没有串相同了,必须从开头进行比较
        while(next[len+1]!=1)
        {//必须是next[len+1]-1,不能是next[len],比如aaaab就不满足next[len]
            res[k++]=next[len+1]-1;
            len=next[len+1]-1;
        }
        for(i=k-1;i>=0;i--)
        printf("%d ",res[i]);
        printf("\n");
    }
    system("pause");
    return 0;
}

原文地址:https://www.cnblogs.com/hpustudent/p/2163269.html