字符串匹配Sunday算法

//
// 字符串匹配 sunday算法
#include <iostream>
#include <string.h>
#include <assert.h>
#include <time.h>
using namespace std;

const char * strMatch(const char *src, const char *need)
{
	int Mlen=strlen(src);
	int Nlen=strlen(need);
	// 1.计算移动距离
	size_t distance[256];
	int i;
	for (i=0; i<256; i++)
	{
		distance[i]=Nlen+1;
	}
	for (i=0; i<Nlen; i++)
	{
		distance[(unsigned char)need[i]]=Nlen-i;
	}

	//2.循环
	int j;
	i=0;
	while (i < Mlen-Nlen+1)
	{
		j=0;
		while(j<Nlen)
		{
			if (src[i]==need[j])
			{
				i++; j++;
				continue;
			}else
			{
				break;
			}
		}
		if (j==Nlen) // 匹配成功
		{
			return src+i-j;
		}else
		{
			i=i-j+distance[src[i-j+Nlen]];
		}
	}

	return NULL;

}
int main()
{
	char str1[]="abcdefghijk";
	char str2[]="cdef";
	char str3[]="cdeh";
	const char *p;
	if (p=strMatch(str1,str2))
	{
		cout<<str1<<"   find "<<str2<<"   result:"<<p<<endl;
	}else
	{
		cout<<str1<<"   NOT FOUND  "<<str2<<endl;
	}
	p=NULL;
	if (p=strMatch(str1,str3))
	{
		cout<<str1<<"   find "<<str3<<"   result:"<<p<<endl;
	}else
	{
		cout<<str1<<"   NOT FOUND  "<<str3<<endl;
	}
	

	int TestN=100000000;
	cout<<endl<<"性能测试  "<<TestN<<"次循环"<<endl;
	time_t ib,ie;
	int N=TestN;
	ib=clock();
	while (N--)
	{
		p=strstr(str1,str2);
	}
	ie=clock();
	cout<<"strstr()  cost "<<ie-ib<<" ms "<<endl;

	N=TestN;
	ib=clock();
	while (N--)
	{
		p=strMatch(str1,str2);
	}
	ie=clock();
	cout<<"strMatch()  cost "<<ie-ib<<" ms "<<endl;

	/
	N=TestN;
	char str4[]="cbdsuhfailfhbuwgfqoefh geuihocurnoqrg wofyhwe8uoifruhhhhhhhhkgaosfyqpgpfhqpr h;ssssshttp://hi.baidu.com/yevqbqwaxdbdfmq/item/5f2fb8dfd0577748fa576852";
	char str5[]="baidu.com/ye";
	ib=clock();
	while (N--)
	{
		p=strstr(str4,str5);
	}
	ie=clock();
	cout<<"strstr()  cost "<<ie-ib<<" ms "<<endl;

	N=TestN;
	ib=clock();
	while (N--)
	{
		p=strMatch(str4,str5);
	}
	ie=clock();
	cout<<"strMatch()  cost "<<ie-ib<<" ms "<<endl;
	return 0;
}



strstr采用BF算法,极慢。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值