1. 程式人生 > >KMP演算法中核心的程式碼

KMP演算法中核心的程式碼

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;

void get_next(string T, int *next)
{
    int i = 1, j = 0;
    next[1] = 0;

    while (i < atoi((char *)&T[0]))
    {
        //cout<<"i: "<<i<<" j:"<<j<<endl;
        if (j == 0 || T[i] == T[j])
        {
            ++i;
            ++j;
            next[i] = j;
        }
        else
            j = next[j];
    }
}