KMP算法

来源:互联网 发布:个人网站 建站 编辑:程序博客网 时间:2024/06/08 05:17

KMP算法:

next函数如图所示:

#include <iostream>using namespace std;#include <cstdio>#include <cstdlib>#include <cstring>int next[100];int getnext(char t[]){    int i = 0,j = -1;    next[0] = -1;    while(i < strlen(t)-1){         if(j == -1 || t[i] == t[j]){              i++;              j++;              next[i] = j;         }else         j = next[j];    }    for(int i = 0;i < strlen(t);i++){         printf("%d ",next[i]);    }    printf("\n");}int main(){    char s[100],t[100];    /* s是原始串,t是被匹配串 */    int i,j;    while(scanf("%s%s",s,t) != EOF){         memset(next,0,sizeof(next));         getnext(t);         i = 0,j = 0;         int lens = strlen(s),lent = strlen(t);         while(i < lens){               if((j == -1) || (s[i] == t[j])){                   i++;                   j++;                   if(j == lent){                       printf("%d ",i - lent);                       j = 0;                   }               }               else{                   j = next[j];               }         }         printf("\n");    }    system("pause");}


0 0
原创粉丝点击