1. 程式人生 > >Kmp求next的值(下標從0開始的)

Kmp求next的值(下標從0開始的)

直接上程式碼:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int next[100];
int n;
int Next(string a)
{
   int i,j;
   next[0]=-1;
   next[1]=0;
   for(i=2;i<n;i++)
   {
       j=next[i-1];
       while(j!=-1 && a[i-1]!=a[j])
       {
           j=next[j];
       }
       next[i]=j+1;
   }
}
int main()
{
    int i;
   string a;
   while(cin>>a)
   {
       n=a.size();
       //cout<<n<<endl;
       Next(a);
       for(i=0;i<n-1;i++)
        cout<<next[i]+1<<" ";
        cout<<next[i]+1<<endl;
   }
   return 0;
}