【数据结构】KMP算法匹配的next数组计算

只是一个普通的demo,考试的时候可能会用到手动计算next数组的情况,这个是代替验证。

目前必须指定maxsize并对字符串赋值。

好久没写c++了下次有空再优化成自动输入的,核心算法体现出来就好:

#include<iostream>
using namespace std;
int maxsize=12;
void getNext(char *str){
    //1.初始化
    int i,j;
    int *next=new int[maxsize];
    j=0;
    next[0]=0;
    //2.比较不相同的情况
    //其中我们规定,j是前缀,i是后缀 
    for(i=1;i<maxsize;i++){
        while(j>0&&str[i]!=str[j]){
            j=next[j-1];
        }
        //3.比较相同的情况 
        if(str[i]==str[j]) j++;
        //4.赋值 
        next[i]=j;
    } 
    //打印
    cout<<"original:"; 
    for(int i=0;i<maxsize;i++) {
        cout<<(++next[i])<<'	';
    }
    cout<<endl;
    //先对next数组进行整体右移,空的补-1
    for(int i=maxsize-1;i>0;i--){
        next[i]=next[i-1];
    } 
    next[0]=-1;
    cout<<"processed:";
    //打印
    for(int i=0;i<maxsize;i++) {
        cout<<(next[i])<<'	';
    }
    
}
int main(){
    char a[]={'a','b','a','b','a','a','a','b','a','b','a','a'};
    getNext(a);
    return 0;
}

截图如下:

原文地址:https://www.cnblogs.com/robotpaul/p/13943405.html