1- package com .thealgorithms .searches ;
2-
31/**
42 * Boyer-Moore string search algorithm
53 * 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
75 */
86public class BoyerMoore {
97
@@ -13,34 +11,40 @@ public class BoyerMoore {
1311
1412 public BoyerMoore (String pat ) {
1513 this .pattern = pat ;
16- this .R = 256 ;
14+ this .R = 256 ; // extended ASCII
1715 this .right = new int [R ];
16+
17+ // Initialize all occurrences as -1
1818 for (int c = 0 ; c < R ; c ++) {
1919 right [c ] = -1 ;
2020 }
21+
22+ // Fill the actual value of last occurrence of a character
2123 for (int j = 0 ; j < pat .length (); j ++) {
2224 right [pat .charAt (j )] = j ;
2325 }
2426 }
2527
2628 public int search (String text ) {
29+ if (pattern .isEmpty ()) return 0 ;
30+
2731 int m = pattern .length ();
2832 int n = text .length ();
29- int skip ;
3033
34+ int skip ;
3135 for (int i = 0 ; i <= n - m ; i += skip ) {
3236 skip = 0 ;
3337 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 ]);
3642 break ;
3743 }
3844 }
39- if (skip == 0 ) {
40- return i ;
41- }
45+ if (skip == 0 ) return i ; // found
4246 }
43- return -1 ;
47+ return -1 ; // not found
4448 }
4549
4650 public static int search (String text , String pattern ) {
0 commit comments