国防科大KMP算法求next数组(下标从0开始,相当于优化后的nextval)

 

#include<bits/stdc++.h>
using namespace std;
int main(){
    char s[105];
    
    while(cin>>s) 
    {
        int next[105];
        memset(next,0,sizeof(next));
        int i=0,j=-1;
        next[0]=-1;
        
        int l=strlen(s);
        while(i<l-1){
            while(j>=0&&s[i]!=s[j]){
                j=next[j];
            }
            i++;j++;
            if(s[i]==s[j]) next[i]=next[j];
            else next[i]=j;
        }
        
        for(int i=0;i<l;i++){
            cout<<next[i]<<" ";
        }
        cout<<endl;
    }
    return 0;
    
}

 

posted on 2020-11-22 16:03  蔡军帅  阅读(390)  评论(0编辑  收藏  举报