1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
| #include <stdio.h> #include <string.h>
#define MAX_CHAR 256 #define SIZE 256 #define MAX(x, y) (x) > (y) ? (x) : (y)
void BoyerMoore(char *pattern, int m, char *text, int n);
int main() { char text[256], pattern[256];
while(1) { scanf("%s%s", text, pattern); if(text == 0 || pattern == 0) break;
BoyerMoore(pattern, strlen(pattern), text, strlen(text)); printf("\n"); }
return 0; }
void print(int *array, int n, char *arrayName) { int i; printf("%s: ", arrayName); for(i = 0; i < n; i++) { printf("%d ", array[i]); } printf("\n"); }
void PreBmBc(char *pattern, int m, int bmBc[]) { int i;
for(i = 0; i < MAX_CHAR; i++) { bmBc[i] = m; }
for(i = 0; i < m - 1; i++) { bmBc[pattern[i]] = m - 1 - i; }
}
void suffix_old(char *pattern, int m, int suff[]) { int i, j;
suff[m - 1] = m;
for(i = m - 2; i >= 0; i--) { j = i; while(j >= 0 && pattern[j] == pattern[m - 1 - i + j]) j--;
suff[i] = i - j; } }
void suffix(char *pattern, int m, int suff[]) { int f, g, i;
suff[m - 1] = m; g = m - 1; for (i = m - 2; i >= 0; --i) { if (i > g && suff[i + m - 1 - f] < i - g) suff[i] = suff[i + m - 1 - f]; else { if (i < g) g = i; f = i; while (g >= 0 && pattern[g] == pattern[g + m - 1 - f]) --g; suff[i] = f - g; } }
}
void PreBmGs(char *pattern, int m, int bmGs[]) { int i, j; int suff[SIZE];
suffix(pattern, m, suff);
for(i = 0; i < m; i++) { bmGs[i] = m; }
j = 0; for(i = m - 1; i >= 0; i--) { if(suff[i] == i + 1) { for(; j < m - 1 - i; j++) { if(bmGs[j] == m) bmGs[j] = m - 1 - i; } } }
for(i = 0; i <= m - 2; i++) { bmGs[m - 1 - suff[i]] = m - 1 - i; }
}
void BoyerMoore(char *pattern, int m, char *text, int n) { int i, j, bmBc[MAX_CHAR], bmGs[SIZE];
PreBmBc(pattern, m, bmBc); PreBmGs(pattern, m, bmGs);
j = 0; while(j <= n - m) { for(i = m - 1; i >= 0 && pattern[i] == text[i + j]; i--); if(i < 0) { printf("Find it, the position is %d\n", j); j += bmGs[0]; return; } else { j += MAX(bmBc[text[i + j]] - m + 1 + i, bmGs[i]); } }
printf("No find.\n"); }
|