#include <stdio.h>
#define MaxSize 30
typedef struct {
char data[MaxSize];
int length;
}SqString;
void StrAssign(SqString& s, char cstr[]) {
int i;
for (i = 0; cstr[i] != '\0'; i++) {
s.data[i] = cstr[i];
}
s.length = i;
}
void GetNextval(SqString t, int nextval[]) {
int j = 0, k = -1;
nextval[0] = -1;
while (j < t.length - 1) {
if (k == -1 || t.data[j] == t.data[k]) {
j++;
k++;
if (t.data[j] != t.data[k]) {
nextval[j] = k;
}
else {
nextval[j] = nextval[k];
}
}
else {
k = nextval[k];
}
}
}
int KMPIndexl(SqString s, SqString t) {
int nextval[MaxSize], i = 0, j = 0;
if (s.length < t.length) {
return (-1);
}
GetNextval(t, nextval);
while (i < s.length && j < t.length) {
if (j == -1 || s.data[i] == t.data[j]) {
i++;
j++;
}
else {
j = nextval[j];
}
}
if (j >= t.length) {
return (i - t.length);
}
else {
return (-1);
}
}
int main() {
char a[] = "abcaabbabcabaacbacba\0";
char b[] = "abcabaa\0";
SqString s1, s2;
StrAssign(s1, a);
StrAssign(s2, b);
int index = KMPIndexl(s1, s2);
if (index == -1) {
printf("未匹配");
}
else {
printf("在目标串的第%d个位置", index+1);
}
return 0;
}
C语言改进的KMP算法
最新推荐文章于 2024-04-18 15:20:01 发布