Horspool(字符串匹配)算法实现 c语言

#include<stdio.h>

#define ASIZE 256

void preBmBc(char *x, int m, int bmBc[]) {
   int i;
 
   for (i = 0; i < ASIZE; ++i)
      bmBc[i] = m;
   for (i = 0; i < m - 1; ++i)
      bmBc[x[i]] = m - i - 1;
}

void HORSPOOL(char *x, int m, char *y, int n) {
   int j, bmBc[ASIZE];
   char c;

   /* Preprocessing */
   preBmBc(x, m, bmBc);

   /* Searching */
   j = 0;
   while (j <= n - m) {
      c = y[j + m - 1];
      if (x[m - 1] == c && memcmp(x, y + j, m - 1) == 0)
         printf("%.*s", m, y +j);
      j += bmBc[c];
   }
   printf("\n");
}



int main()
{
    char *pattern = "hello";
    char *buf = "hehe  hello world";
    HORSPOOL(pattern, strlen(pattern), buf, strlen(buf));
    return 0;
}

 

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注