Advertisement
cd62131

Boyer-Moore String Search

Jan 25th, 2018
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.06 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. static int calc_skip(char *);
  6. static int faster_match(char *, char *, int);
  7.  
  8. #define CHARS 128
  9. static int skip[CHARS];
  10.  
  11. int main(void) {
  12.   char *text = "XYXZde0XZZkWXYZ";
  13.   char *pattern = "WXYZ";
  14.   int n = strlen(text);
  15.   int ret = faster_match(text, pattern, n);
  16.   if (ret < 0) {
  17.     exit(1);
  18.   }
  19.   printf("%d\n", ret);
  20.   printf("%s\n", text + ret);
  21. }
  22.  
  23. static int calc_skip(char *pattern) {
  24.   int i, m;
  25.   m = strlen(pattern);
  26.   for (i = 0; i < CHARS; ++i) {
  27.     skip[i] = m;
  28.   }
  29.   for (i = 0; i < m; ++i) {
  30.     skip[(int) pattern[i]] = m - i - 1;
  31.   }
  32.   return m;
  33. }
  34.  
  35. static int faster_match(char *text, char *pattern, int n) {
  36.   int m = calc_skip(pattern) - 1;
  37.   int i = m, j;
  38.   while (i < n) {
  39.     j = m;
  40.     while (j >= 0) {
  41.       if (text[i] == pattern[j]) {
  42.         if (j == 0) {
  43.           return i;
  44.         }
  45.         --i, --j;
  46.       } else {
  47.         break;
  48.       }
  49.     }
  50.     i += (skip[(int) text[i]] > m - j ? skip[(int) text[i]] : m - j + 1);
  51.   }
  52.   return -1;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement