- 论坛徽章:
- 0
|
- /*
- * A class for string matching use the
- * Backward Nondeterministic Dawg Matching algorithm
- *
- * 2008/2/26
- *
- * By Yao Jianming
- */
- #ifndef _BNDMMATCH_H
- #define _BNDMMATCH_H
- #ifndef STRMATCH_MAXCHER
- #define STRMATCH_MAXCHER 256
- #endif
- #include <string>
- class strmatch {
- private:
- std::string str;
- int mask[STRMATCH_MAXCHER];
- void makemasktable();
- public:
- strmatch(const char* p) : str(p) {makemasktable();}
- void* search(const void* haystack, size_t haystack_len) const;
- };
- #endif
- #include "strmatch.h"
- void strmatch::makemasktable()
- {
- memset(mask, 0, STRMATCH_MAXCHER*sizeof(int));
- const char* patt = str.c_str();
- int len = str.size();
- int s =1;
- for(int i = len - 1; i >= 0; --i) {
- mask[patt[i]] |= s;
- s <<= 1;
- }
- }
- void* strmatch::search(const void* haystack, size_t haystack_len) const
- {
- const char* text = (const char*)haystack;
- const char* patt = str.c_str();
- int len = str.size();
- int k = 0;
- while(k <= haystack_len - len) {
- int i, d = ~0, shift = len;
- for(i = len - 1; i >= 0 && d != 0; --i) {
- d &= mask[text[k+i]];
- d <<= 1;
- }
- if(i < 0 && d != 0)
- return (void*)(text + k + i + 1);
- if(text[k+i+2] == patt[0])
- shift = i + 2;
-
- k += shift;
- }
-
- return (void*)NULL;
- }
- #include <sys/time.h>
- #include "strmatch.h"
- main()
- {
- struct timeval start, end;
- gettimeofday(&start, 0);
- strmatch str = "helloworld";
- char text[] = "aaaadfjdfddfdkfalhelloworld";
- char* p = (char*)str.search(text, strlen(text));
- if(p != NULL) printf("%s\n", p);
- gettimeofday(&end, 0);
- long ltime = (end.tv_sec - start.tv_sec) * 1000000 +
- end.tv_usec - start.tv_usec;
- printf("ltime: %ld\n", ltime);
- }
复制代码
试过了能用,各位给看看,哪里需要改进
[ 本帖最后由 yjm0573 于 2008-2-29 10:10 编辑 ] |
|