【数据结构の一些复盘】HM5_字符串匹配——KMP算法及其优化

 //第一,请实现KMP算法;

//第二,考虑KMP算法的优化,以模式串为aaaaaaaaaaab为例

//第一,请实现KMP算法;
//第二,考虑KMP算法的优化,以模式串为aaaaaaaaaaab为例

#include <iostream>
#include <string>
using namespace std;
#define MAXSTRLEN 255//用户可在255以内定义最大串长

typedef struct {
	char ch[MAXSTRLEN];
	int length;
}SString;

bool StrAssign(SString& T, char* chars) {
	//生成一个其值等于串常量chars的串T
	int i = 1;
	while (chars[i - 1] && i < 255) {
		T.ch[i] = chars[i - 1];
		i++;
	}
	if (i == 255 && chars[i]) {
		return 0;
	}
	T.length = i - 1;
	return true;
}

void get_next(SString T, int next[]) {
	int i = 1, j= 0;
	next[1] = 0;
	while (i < T.length) {
		if (j == 0 || T.ch[i] == T.ch[i]) {
			i++;
			j++;
			next[i] = j;
		}
		else {
			j = next[j];
		}
	}
}

void get_nextval(SString T, int next[]) {
	int i, m;//i为字符串下标,m为最大相同前后缀大小
	next[0] = 0;
	for (i = 1, m = 0;i < T.length;i++) 
	{
		if (T.ch[i] == T.ch[m])
			next[i] = next[m];
		else
			next[i] = m;
		while (m > 0 && T.ch[i] != T.ch[m])
		{
			m = next[m - 1];
		}
		if (T.ch[i] == T.ch[m])
		{
			m++;
		}
	}
}
int Index_KMP(SString S, SString T) {
	int i = 1;
	int j = 1;
	int* next = new int(T.length + 1);
	get_next(T, next);
	while (i <= S.length && j <= T.length) {
		if (j == 0 || S.ch[i] == T.ch[j]) {
			i++;
			j++;
		}
		else {
			j = next[j];
		}
	}
	delete next;
	if (j > T.length) {
		return i - j + 1;
	}
	else {
		return 0;
	}
}

int Index_KMPval(SString S, SString T) {
	int i = 1;
	int j = 1;
	int* next = new int(T.length + 1);
	get_nextval(T, next);
	while (i <= S.length && j <= T.length) {
		if (j == 0 || S.ch[i] == T.ch[j]) {
			i++;
			j++;
		}
		else {
			j = next[j];
		}
	}
	delete next;
	if (j > T.length) {
		return i - j + 1;
	}
	else {
		return 0;
	}
}
int main() {
	char s1[255] = "aaaaaaaaaaab";
	char s2[255] = "aaaab";

	SString S1, S2;
	StrAssign(S1, s1);
	StrAssign(S2, s2);
	cout <<"优化前:"<< Index_KMP(S1, S2);
	cout << "优化后:" << Index_KMPval(S1, S2);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值