File tree Expand file tree Collapse file tree
src/main/java/com/thealgorithms/searches Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .thealgorithms .searches ;
2+
3+ /**
4+ * Boyer-Moore string search algorithm
5+ * Efficient algorithm for substring search.
6+ *
7+ * @author Pau
8+ */
9+
10+ public class BoyerMoore {
11+
12+ private final int R ;
13+ private int [] right ;
14+ private String pattern ;
15+
16+ public BoyerMoore (String pat ) {
17+ this .pattern = pat ;
18+ this .R = 256 ;
19+ this .right = new int [R ];
20+ for (int c = 0 ; c < R ; c ++)
21+ right [c ] = -1 ;
22+ for (int j = 0 ; j < pat .length (); j ++)
23+ right [pat .charAt (j )] = j ;
24+ }
25+
26+ public int search (String text ) {
27+ int m = pattern .length ();
28+ int n = text .length ();
29+ int skip ;
30+
31+ for (int i = 0 ; i <= n - m ; i += skip ) {
32+ skip = 0 ;
33+ 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 )]);
36+ break ;
37+ }
38+ }
39+ if (skip == 0 )
40+ return i ;
41+ }
42+ return -1 ;
43+ }
44+
45+ public static int search (String text , String pattern ) {
46+ return new BoyerMoore (pattern ).search (text );
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments