首页 > 编程语言 > 详细

KMP算法

时间:2015-05-06 21:05:03      阅读:235      评论:0      收藏:0      [点我收藏+]

对于KMP算法,最重要的是要把握其中的next数组的含义及求法

考虑一个模式字符串:b1b2...bn,定义next[s]如下:

next[s]  is the longest proper prefix of b1b2...bs that is also a suffix of b1b2...bs

#include<iostream>
#include<string.h>
using namespace std;
void makeNext(char *s, int *next){
    int len = strlen(s);
    int j = 0;
    for(int i = 1; i < len; i++){
       while(j > 0 && s[j + 1 - 1] != s[i + 1 - 1])
           j = next[j];
       if(s[j + 1 - 1] == s[i + 1 - 1]){
            j += 1;
            next[i + 1] = j;
        }
        else
           next[i + 1] = 0;
    }
}
int main(){
    char src[] = "ababaa";
    char src1[] = "abababaab";
    char src2[] = "aaaaaa";
    char src3[] = "abbaabb";
    int *next, *next1, *next2, *next3;
    next = new int[strlen(src) + 1];
    memset(next, 0, (strlen(src) + 1) * sizeof(int));
    makeNext(src, next);
    next1 = new int[strlen(src1) + 1];
    memset(next1, 0, (strlen(src1) + 1) * sizeof(int));
    makeNext(src1, next1);
    next2 = new int[strlen(src2) + 1];
    memset(next2, 0, (strlen(src2) + 1) * sizeof(int));
    makeNext(src2, next2);
    next3 = new int[strlen(src3) + 1];
    memset(next3, 0, (strlen(src3) + 1) * sizeof(int));
    makeNext(src3, next3);
    return 0;
}

 

KMP算法

原文:http://www.cnblogs.com/hustxujinkang/p/4483045.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!