C++KMP字符串匹配

#include<iostream>
#define defaultsize 30
using namespace std;


typedef struct {
	char*ch;
	int maxsize;
	int n;
}HString;

void HStringInit(HString&S, int n=defaultsize)
{
	if (n < defaultsize)
		n = defaultsize;
	S.ch = new char[n];
	S.maxsize = n;
	S.n = n;
}

void CreateHString(HString&S, char c[])
{
	int i = 0;
	while (c[i] != '\0'&&i<S.maxsize)
	{
		S.ch[i] = c[i];
		i++;
	}
	if (c[i] != '\0')
		cout << "超出存储空间" << endl;
	else
		S.n = i;
}


void Print(HString&S)
{
	for (int i = 0;i < S.n;i++)
		cout << S.ch[i] << " ";
}

int find(const HString&T, const HString&P)
{
	for (int i = 0;i < T.n - P.n+1;i++)
	{
		int j = 0;
		for (j = 0;j < P.n;j++)
		{
			if (P.ch[j] != T.ch[j + i])
				break;
		}
		if (j == P.n&&P.ch[j] == T.ch[i+j])
		{
			return i;
		}

	}
}

void GetNext(HString&S, int next[])
{
	int j = 0, k = -1;next[j] = k;
	while(j<S.n)
	{
		while (k >= 0 && S.ch[k] != S.ch[j])k = next[k];
		j++;k++;
		if (S.ch[k] == S.ch[j])next[j] = next[k];
		else next[j] = k;
	}
}

int FastFind(HString&T, HString&P,int next[])
{
	int i = 0, j = 0;
	while (i < T.n&&j < P.n)
	{
		if (j == -1 || T.ch[i] == P.ch[j]) { i++;j++; }
		else j = next[j];
	}
	if (j < P.n)return -1;
	else return i - P.n;
}


int main()
{
	HString S1;
	HString S2;
	HStringInit(S1);
	HStringInit(S2);
	char c1[] = "dad";
	char c2[] = "aadad";
	CreateHString(S1, c1);
	CreateHString(S2, c2);
	Print(S1);
	Print(S2);
	int next[sizeof(c1) / sizeof(char)];
	GetNext(S1, next);
	cout << FastFind(S2, S1, next);
	system("pause");
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值