[算法学习笔记]寻找子字符串第一次出现位置

本文详细介绍了BF算法和KMP算法的区别,并通过实例代码进行对比演示,旨在帮助读者理解这两种字符串匹配算法的特点。

使用了需要回溯的BF算法和不需要回溯的KMP算法,本文纯属个人学习笔记。

//

#include "stdafx.h"
#include <iostream>
using namespace std;
int BF(const char* src, const char* dst);
int KMP(const char* src, const char* dst);
void KMP_next(const char* src, int* next);

int BF(const char* src, const char* dst)
{
	int i,j;
	i = 0;
	int srcLen = strlen(src);
	int dstLen = strlen(dst);

	while (i < srcLen)
	{
		j = 0;
		while ((src[i] == dst[j]) && (j <dstLen))
		{
			i++;
			j++;
		}

		if (j == dstLen)
		{
			return (i - j);
		}

		i = i - j + 1;
	}

	return -1;
}

int KMP(const char* src, const char* dst)
{
	int next[100];
	int i = 0, j = 0;

	int srcLen = strlen(src);
	int dstLen = strlen(dst);

	KMP_next(src, next);

	while (i < srcLen)
	{
		if ((-1 == j) || (src[i] == dst[j]))
		{
			i++;
			j++;
		}
		else
		{
			j = next[j];
		}

		if (j == dstLen)
		{
			return (i - j);
		}
	}

	return -1;
}

void KMP_next(const char* src, int* next)
{
	int j = 0, k = -1;
	next[0] = -1;
	int srcLen = strlen(src);

	while (j < (srcLen - 1))
	{
		if ((-1 == k) || (src[j] == src[k]))
		{
			j++;
			k++;
			next[j] = k;
		}
		else
		{
			k = next[k];
		}
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	const char* src = "abcdegfhjfdscdcdhakjgrs";
	const char* dst = "cdha";
	//int position = BF(src, dst);
	int position = KMP(src, dst);

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值