数据结构(之)KMP算法


// KMP_algorithm.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include<iostream>
using namespace std;

class KMP
{
private:
public:
	//KMP();
	void matchStr(char source[], char match[]);
	void getNext(char match[], int length, int next[]);
	int findStr(char source[], int slength, char match[], int mlength, int next[]);
};
int KMP::findStr(char source[], int slength, char match[], int mlength, int next[])
{
	int i=0, j=0;
	while(i<slength && j<mlength)
	{
		if(j==-1 || source[i]==match[j])
		{
			i++;
			j++;
		}
		else
			j=next[j];
	}
	if(j>=mlength-1)
		return i-mlength+1;
	else
		return 0;
}
void KMP::matchStr(char source[], char match[])
{
	int slength = 0;
	int mlength = 0;
	while(source[slength]!='\0')
		slength++;
	while(match[mlength]!='\0')
		mlength++;
	int* next=new int[mlength];
	getNext(match, mlength, next);
	int result;
	result=findStr(source,  slength, match,  mlength, next);
	cout<<"Result is: "<<result<<endl;
	delete[] next;
}
void KMP::getNext(char match[], int mlength, int next[])
{
	int i=0, k=-1;
	//int next[length];
	next[0]=-1;
	while(i<mlength-1)
	{
		while(k>=0 && match[i]!= match[k])
			k=next[k];
		i++;
		k++;
		if(match[i] == match[k])
			next[i]=next[k];
		else
			next[i]=k;
	}
}
int main()
{
	char source[]="babddebdbdy";
	char match[]="bdy";
	KMP kp;
	kp.matchStr(source, match);
}

结果如下:


KMP算法是一种字符串匹配算法,用于在一个较长的字符串中查找一个较短的模式串。它通过构建next数组来实现快速匹配。 KMP算法的核心思想是在每次失配时,不是将模式串向后移动一位,而是将模式串向后移动至下一次可以和前面部分匹配的位置,从而跳过大部分的失配步骤。这样可以大大提高匹配效率。 next数组是部分匹配值表,它存放的是每一个下标对应的部分匹配值。部分匹配值是指前缀和后缀的最长共有元素的长度。通过构建next数组,可以在匹配过程中根据当前失配的位置快速确定模式串的移动步数。 下面是手动模拟KMP算法的过程: 1. 首先,根据模式串构建next数组。假设模式串为p[],长度为m。初始化next数组,next = -1,next = 0。 2. 从第2个位置开始,依次计算next[i]的值。假设已经计算到next[i-1],则比较p[i-1]和p[next[i-1]]的值: - 如果p[i-1]等于p[next[i-1]],则next[i] = next[i-1] + 1; - 如果p[i-1]不等于p[next[i-1]],则将next[i-1]的值赋给j,然后继续比较p[i-1]和p[j]的值,直到找到一个满足p[i-1]等于p[j]的位置或者j等于0为止。此时,next[i] = j。 3. 完成next数组的构建后,开始匹配过程。假设待匹配的字符串为s[],长度为n。初始化i = 0,j = 0。 4. 依次比较s[i]和p[j]的值: - 如果s[i]等于p[j],则i和j分别向后移动一位; - 如果s[i]不等于p[j],则根据next数组确定模式串的移动步数。将j移动到next[j]的位置,即j = next[j]。 5. 重复步骤4,直到匹配成功(j等于模式串的长度m)或者遍历完整个字符串s。 通过上述步骤,可以实现高效的字符串匹配。KMP算法的时间复杂度为O(n+m),其中n为字符串s的长度,m为模式串p的长度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值