您的位置:首页 > 编程语言 > Go语言

小算法--KMP

2013-03-14 22:57 363 查看
#include <stdio.h>
#include <stdlib.h>

#define MAXSTRLEN 255
typedef unsigned char String[MAXSTRLEN + 1];

int main(void)
{
int Index_KMP(String S, String T, int next[], int pos);//利用模式串T的next求T在主串S中第pos个字符之后的位置的KMP算法
void get_next(String, int[]);//求模式串T的next值

int next[MAXSTRLEN + 1] = {0};
String S=" acabaabaabcacaabc";//主串
String T=" abaabcac";//模式串
S[0] = 17;
T[0] = 8;

get_next(T, next);

printf("%d\n", Index_KMP(S, T, next, 1));

return EXIT_SUCCESS;
}

int Index_KMP(String S, String T, int next[], int pos)
{
int i = pos, j = 1;
while (i <= S[0] && j <= T[0]) {
if (0 == j || S[i] == T[j]) {
i++;j++;
} else {
j = next[j];
}
}

if (j > T[0]) {
return i - T[0];
} else {
return 0;
}
}
void get_next(String T, int next[])
{
int i = 1, j = 0;
next[1] = 0;

while (i < T[0]) {
if (0 == j || T[i] == T[j]) {
i++;j++;
if (T[i] != T[j]) {
next[i] = j;
} else {
next[i] = next[j];
}
} else {
j = next[j];
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息