字符串匹配Sunday算法
2012-12-02 20:47
351 查看
// // 字符串匹配 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算法,极慢。
相关文章推荐
- 字符串匹配算法——Sunday算法和KMP算法(java版本)
- 字符串匹配算法之Sunday算法的学习笔记
- 字符串匹配之Sunday算法
- PHP实现的字符串匹配算法示例【sunday算法】
- 字符串匹配---Sunday算法
- 字符串匹配的Sunday算法--性能上超过KMP和BM算法
- 字符串匹配 sunday算法
- 字符串匹配---sunday算法实现(转)
- 字符串匹配算法 – Sunday算法
- 字符串匹配--sunday算法
- 字符串匹配算法之sunday算法
- php实现字符串匹配算法——sunday算法
- sunday算法研究——超越kmp的字符串匹配
- sunday算法和自己关于字符串匹配的一些思考
- 字符串匹配Sunday算法C++实现
- 字符串匹配的sunday算法
- 字符串匹配-sunday算法
- 字符串匹配算法之sunday算法
- 字符串匹配之Sunday算法
- 字符串匹配——Sunday算法