1
- package com .thealgorithms .searches ;
2
-
3
1
/**
4
2
* Boyer-Moore string search algorithm
5
3
* Efficient algorithm for substring search.
6
- * https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search-algorithm
4
+ * https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm
7
5
*/
8
6
public class BoyerMoore {
9
7
@@ -13,34 +11,40 @@ public class BoyerMoore {
13
11
14
12
public BoyerMoore (String pat ) {
15
13
this .pattern = pat ;
16
- this .R = 256 ;
14
+ this .R = 256 ; // extended ASCII
17
15
this .right = new int [R ];
16
+
17
+ // Initialize all occurrences as -1
18
18
for (int c = 0 ; c < R ; c ++) {
19
19
right [c ] = -1 ;
20
20
}
21
+
22
+ // Fill the actual value of last occurrence of a character
21
23
for (int j = 0 ; j < pat .length (); j ++) {
22
24
right [pat .charAt (j )] = j ;
23
25
}
24
26
}
25
27
26
28
public int search (String text ) {
29
+ if (pattern .isEmpty ()) return 0 ;
30
+
27
31
int m = pattern .length ();
28
32
int n = text .length ();
29
- int skip ;
30
33
34
+ int skip ;
31
35
for (int i = 0 ; i <= n - m ; i += skip ) {
32
36
skip = 0 ;
33
37
for (int j = m - 1 ; j >= 0 ; j --) {
34
- if (pattern .charAt (j ) != text .charAt (i + j )) {
35
- skip = Math .max (1 , j - right [text .charAt (i + j )]);
38
+ char txtChar = text .charAt (i + j );
39
+ char patChar = pattern .charAt (j );
40
+ if (patChar != txtChar ) {
41
+ skip = Math .max (1 , j - right [txtChar ]);
36
42
break ;
37
43
}
38
44
}
39
- if (skip == 0 ) {
40
- return i ;
41
- }
45
+ if (skip == 0 ) return i ; // found
42
46
}
43
- return -1 ;
47
+ return -1 ; // not found
44
48
}
45
49
46
50
public static int search (String text , String pattern ) {
0 commit comments