Skip to content

Commit 78a9c40

Browse files
authored
Add Boyer-Moore string search algorithm
1 parent 7602f1e commit 78a9c40

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
}

0 commit comments

Comments
 (0)