KMP中求next數組算法實現

#include <iostream>
#include <string>
#include <vector>
using namespace std;
void get_next(char* T,int *next)//C語言版本
{
    int i = 1, j = 0;
    next[1] = 0;
    while (i < T[0])
    {
        if (0 == j || T[i] == T[j])
        {
            ++i;
            ++j;
            next[i] = j;
        }
        else
        {
            j = next[j];
        }
    }
}
vector<int> get_next1(string T)//C++版本
{
    vector<int> next(T.size());
    int i = 0, j = -1;
    next[0] = -1;
    while (i < T.size()-1)
    {
        if (-1 ==j || T[i] == T[j])
        {
            ++i;
            ++j;
            next[i] = j;
        }
        else
        {
            j = next[j];
        }
    }
    return next;
}
int KMP()
{
    return 0;
}
int main()
{
    /*char a[14] = " ababaaababaa";//第一個空格一定要加上
    a[0] = 12;
    int n[13];
    get_next(a, n);
    for (int i = 1; i < 13; ++i)
         printf("%d ",n[i]);
    getchar();
    return 0;*/
    
    string a = "ababaaababaa";
    vector<int> n = get_next1(a);
    for (int i = 0; i < n.size(); ++i)
        cout << n[i]<<' ';
    cout << endl;
    cin.get();
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章