Node:KMP之next数组

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <stack>
#include <queue>

using namespace std;
const int maxn=1010;
int pos[maxn];
int n;
/*
KMP算法中的next数组求法
图解:
|**************0000000000**************.....................|
               j(next[i])              i
|****000000****|
     next[j]   j(next[i])
    next[ next[i] ]
    ...

假设咱们已经找到了字符串t的i位置,next[1...i]已知,当前j跟踪的是next[i]的位置
初始化 j = next[i] = next[0] = -1; i = 0;
那么,对于下一个状态 i + 1,求next数组有:
1.if t[i] == t[j]
    next[i + 1] = j + 1 = next[next[i] + 1];
2.if t[i] != t[j]
    see if t[next[j]] == t[i + 1]

*/

void getNext(char* p)
{
    //初始化
    int i = 0, j = -1;
    int len = strlen(p);

    //next数组和j的关系
    pos[i] = j;

    /*i只会增加不会减少,所以算法是线性的,j会根据匹配情况向前回溯,
    /*下面两个循环等效
    while(i < len)
    {
        while(j >= 0 && p[i] != p[j])
            j = pos[j];
        i++,j++;
        pos[i] = j;
    }
    */
    while(i < len - 1)
    {
        if( j == -1 || p[i] == p[j])
        {
            i++;
            j++;
            pos[i] = j;
        }
        else
            j = pos[j];
    }

}

int main()
{
    char in[maxn];

    while(scanf("%s",in))
    {
        getNext(in);
        for(int i = 0; i < strlen(in); i++)
            cout << " " << in[i];
        cout << endl;
        for(int i = 0; i < strlen(in); i++)
            cout << " " << pos[i];
        cout << endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值