#include<iostream>
#include<cstdlib>
#include<cstdio>
#define MAXLEN 255
#define OK 1
#define ERROR -1
typedef struct sstring {
char ch[MAXLEN + 1];
int length;
}SString;
int index_BFmatch_string(SString S, SString T, int pos);
int index_KMPmatch_string_0(SString S, int* next, SString T, int pos);
int* KMP_create_nextArray(SString T);
int index_KMPmatch_string_1(SString S, SString T, int pos);
int* KMP_create_nextArray_pro(SString T);
int main() {
SString s = { "-ababaaababaa",12 };
int* temp = KMP_create_nextArray(s);
for (int i = 0; i <= 12; ++i) {
std::cout << temp[i] <<" " << std::ends;
}
std::cout << std::endl;
SString t = { "-aaaaaaababaa",12 };
int* temp_1 = KMP_create_nextArray_pro(t);
for (int i = 0; i <= 12; ++i) {
std::cout << temp_1[i] << " " << std::ends;
}
}
int index_BFmatch_string(SString S, SString T, int pos) {
int i = pos;
int 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;
}
}
int index_KMPmatch_string_0(SString S,int* next,SString T,int pos){
int i = pos;
int j = 1;
while (i <= S.length && j <= T.length) {
if (S.ch[i] == T.ch[j]) {
++i;
++j;
}
else {
j = next[j];
}
}
if (j > T.length) {
return i - T.length;
}
else {
return 0;
}
}
int* KMP_create_nextArray(SString T){
int i = 1;
int j = 0;
int * next = (int *)malloc(sizeof(int)*(T.length+1));
if (!next) {
exit(-1);
}
next[1] = 0;
while (i < T.length) {
if (j == 0 || T.ch[i] == T.ch[j]) {
++j;
++i;
next[i] = j;
}
else {
j = next[j];
}
}
return next;
}
int index_KMPmatch_string_1(SString S,SString T,int pos){
int i = pos;
int j = 1;
int* next = KMP_create_nextArray(T);
while (i <= S.length && j <= T.length) {
if (S.ch[i] == T.ch[j]) {
++i;
++j;
}
else {
j = next[j];
}
}
if (j > T.length) {
return i - T.length;
}
else {
return 0;
}
}
int* KMP_create_nextArray_pro(SString T) {
int i = 1;
int j = 0;
int* next = (int*)malloc(sizeof(int) * (T.length + 1));
if (!next) {
exit(-1);
}
next[1] = 0;
while (i < T.length) {
if (j == 0 || T.ch[i] == T.ch[j]) {
++j;
++i;
if (T.ch[i] == T.ch[j]) {
next[i] = next[j];
}
else {
next[i] = j;
}
}
else {
j = next[j];
}
}
return next;
}
字符串匹配:kmp算法、BF算法的初步实现。
最新推荐文章于 2024-10-02 08:00:00 发布