KMP简单模板

来源:互联网 发布:兄弟情义歌曲网络歌手 编辑:程序博客网 时间:2024/06/07 10:02

KMP代码:

#include <stdio.h>#include <string.h>#define N 100 int KMP(char s[], char t[], int lens, int lent);void GetNext(char t[], int lent);int next[N];int main(){char s[N], t[N];printf("请输入母串: ");scanf("%s", s);printf("请输入子串:") ;scanf("%s", t) ;int lens = strlen(s);int lent = strlen(t);int pos = KMP(s, t, lens, lent);if(pos == -1){// 返回值为 -1 代表未找到 printf("Not Found!\n");}else{printf("匹配位置:%d\n",pos);// 从0开始 }return 0;}int KMP(char s[], char t[], int lens, int lent)//s:母串   t:字串 {GetNext(t, lent);// 求得next数组 int i = 0, j = 0;while(i < lens && j < lent){if(j == -1 || s[i] == t[j]){i ++;j ++;}else{j = next[j];}}if(j == lent){return i - lent;}else{return -1;}}void GetNext(char t[], int lent){int i = 0, j = -1;next[0] = -1;while(i < lent){if(j == -1 || t[i] == t[j]){i ++;j ++;next[i] = j;}else{j = next[j];}}}
时间复杂度是O(n+m)

0 0
原创粉丝点击