#include <stdio.h>
#define MAXLEN 255
typedef struct {
char ch[MAXLEN];
int length;
} SString;
typedef struct {
char ch[MAXLEN];
int length;
} TString;
//朴素模式匹配算法
int Index(SString S, TString T) {
int i = 1, j = 1;
while (i <= S.length && j <= T.length) {
if (S.ch[i] == T.ch[j]) {
++i;
++j; //继续比较后面字符
} else {
i = i - j + 2;
j = 1; //指针后退继续开始匹配
}
}
if (j < T.length)
return i - T.length;
else
return 0;
}
//KMP算法
int Index_KMP(SString S, TString T, int next[]) {
int i = 1, j = 1;
while (i<=S.length && j<=T.length){
if (j==0||S.ch[i] == T.ch[j]){
++i;
++j;
}
else
j = next[i];
}
if (j>T.length)
return i - T.length;
else
return 0;
}
int main() {
int next[7] = {0, 0, 1, 1, 2, 2, 3};
int Index(SString, TString);
int Index_KMP(SString, TString, next[]);
return 0;
}
数据结构(7)——串的朴素模式匹配算法和KMP算法
最新推荐文章于 2024-06-01 23:14:10 发布