KMP字符串匹配算法

1、

KMP算法是一种线性时间复杂的字符串匹配算法,它是对BF算法(Brute-Force,最基本的字符串匹配算法的)改进。

    对于给的的原始串S和模式串P,需要从字符串S中找到字符串P出现的位置的索引。

 

    BF算法的时间复杂度O(strlen(S) * strlen(T)),空间复杂度O(1)。

   KMP算法的时间复杂度O(strlen(S) + strlen(T)),空间复杂度O(strlen(T))。

 

2、

一个KMP算法,说白了就是构造最大后缀长度数组。

KMP算法与BF算法的区别在于,字符串失配时的处理。

KMP利用之前已经匹配好的位置,将字符串的移动次数降低,移动的步子增大。

 

3、

#include <iostream>   
#include <string>
using namespace std;
int kmp_find(const string& target,const string& pattern)
{
	const int pattern_length = pattern.size();
	const int target_length = target.size();
	int *overlay_function = new int [pattern_length];
	int index;

	overlay_function[0] = -1;
	for(int i = 1; i< pattern_length; i++)
	{
		index = overlay_function[i-1];

		while(index >= 0 && pattern[i] != pattern[index+1] )
		{
			index = overlay_function[index];
		
		}
		if(pattern[i] == pattern[index+1])
		{
			overlay_function[i] = index+1;
		}
		else 
			overlay_function[i] = -1;
	
	}	

	//match algrithm start
	int target_index=0;
	int pattern_index=0;
	while(target_index < target_length&& pattern_index < pattern_length)
	{
		if(target[target_index] ==pattern[pattern_index])
		{
			++target_index;
			++pattern_index;		
		}
		else if(pattern_index == 0)
		{
		++target_index;
		}
		else 
		{
			pattern_index = overlay_function[pattern_index-1] + 1;
		
		}	
	
	}

	delete [] overlay_function;

	if(pattern_index == pattern_length)
		return target_index - pattern_length;
	else 
		return -1;
	
}

void main()  
{  
	string source = "asdsdadwridisdaabaabcabacsdshdsads";
	string pattern = "abaabcabac";
	cout<<kmp_find(source,pattern)<<endl;
		
}  


 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值