#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAXSIZE 256
typedef struct string {
char chs[MAXSIZE];
int length;
}String;
int f[MAXSIZE];
int LengthCHAR(char* s) {
int i = 0;
while ((s[i]) != '\0') {
i++;
}
return i;
}
//模式匹配KMC算法
int IndexKMP(String s, String p, int pos) {
int i = pos, j = 0;
int n = s.length,
m = p.length;
while (i < n && j<m) {
if (j == -1 || s.chs[i] == p.chs[j]) {
i++;
j++;
}
else {
j = f[j];
}
}
return ((j == m) ? i - m : -1);
}
//计算失败函数
void Fail(String p, int* f) {
int j = 0, k = -1;
f[0] = -1;
while (j < p.length) {
if (k == -1 || p.chs[j] == p.chs[k]) {
j++; k++;
f[j] = k;
}
else {
k = f[k];
}
if (j == p.length) {
break;
}
}
}
void PrintString(String* s) {
printf("Output the String:\n");
printf("%s\n", s->chs);
}
void main() {
String* s, * p;
int size_ss, size_pp;
char ss[MAXSIZE] = "zzzzzzabcabcaabcabcabbacb"; //长度不得大于 MAXSIZE
char pp[MAXSIZE] = "abcabcabbac"; //长度不得大于 MAXSIZE
s = (String*)malloc(sizeof(String));
p = (String*)malloc(sizeof(String));
size_ss = LengthCHAR(ss);
size_pp = LengthCHAR(pp);
strcpy_s(s->chs, size_ss+1 ,ss); //加一的目的是字符串的结尾有一个'\0'
strcpy_s(p->chs, size_pp+1 ,pp); //加一的目的是字符串的结尾有一个'\0'
s->length = LengthCHAR(ss);
p->length = LengthCHAR(pp);
PrintString(s);
PrintString(p);
Fail(*p, f);
printf("%d\n", IndexKMP(*s, *p, 0));
printf("*************\n");
}
字符串-模式匹配-KMP算法
猜你喜欢
转载自blog.csdn.net/m0_47472749/article/details/121735997
今日推荐
周排行