字符串匹配:kmp算法、BF算法的初步实现。

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值