KMP-快速模式匹配算法
KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt同时发现,因此人们称它为克努特——莫里斯——普拉特操作(简称KMP算法)。KMP算法的关键是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是实现一个next()函数,函数本身包含了模式串的局部匹配信息。
实现语言:
C语言
形参:
sourse[] 主字符串
pattern[] 模式字符串
返回值:
模式字符串在主字符串种匹配成功时第一个字符所在的位置,若没有匹配成功,则返回-1.
实现代码:
int BMPStringCompare(char sourse[], char pattern[]) {
int pointS = 0, pointP = 0, lengthP = 0, *next;
while (pattern[lengthP++] != '\0');
lengthP--;
next = (int *)malloc(sizeof(int)*(lengthP));
next[0] = -1;
next[1] = 0;
for (int i = 1; i < lengthP; i++) {
while (pointP > 0 && pattern[i] != pattern[pointP])pointP = next[pointP];
if (pattern[i] == pattern[pointP])pointP++;
next[i + 1] = pointP;
}
pointP = 0;
while (1) {
if (pattern[pointP] == '\0'){
free(next);
return pointS - pointP + 1;
}
else if (sourse[pointS] == '\0') {
free(next);
return -1;
}
else if (pointP == -1 || sourse[pointS] == pattern[pointP])pointP++, pointS++;
else pointP = next[pointP];
}
}