码迷,mamicode.com
首页 > 编程语言 > 详细

KMP算法

时间:2015-05-06 21:08:11      阅读:143      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!