Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions src/main/java/com/thealgorithms/searches/BoyerMoore.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,25 @@
package com.thealgorithms.searches;

import java.util.HashMap;
import java.util.Map;

/**
* Boyer-Moore string search algorithm.
* Efficient algorithm for substring search.
* https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm
*/
public class BoyerMoore {

private final int radix; // Radix (number of possible characters)
private final int[] right; // Bad character rule table
private final Map<Character, Integer> right; // Bad character rule table: last index of each pattern character
private final String pattern;

public BoyerMoore(String pat) {
this.pattern = pat;
this.radix = 256;
this.right = new int[radix];

for (int c = 0; c < radix; c++) {
right[c] = -1;
}
// A map instead of a 256-entry array, so characters outside extended ASCII work too
this.right = new HashMap<>();

for (int j = 0; j < pat.length(); j++) {
right[pat.charAt(j)] = j;
right.put(pat.charAt(j), j);
}
}

Expand All @@ -40,7 +38,7 @@ public int search(String text) {
char txtChar = text.charAt(i + j);
char patChar = pattern.charAt(j);
if (patChar != txtChar) {
skip = Math.max(1, j - right[txtChar]);
skip = Math.max(1, j - right.getOrDefault(txtChar, -1));
break;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,11 @@ public void testStaticSearchMethod() {
int index = BoyerMoore.staticSearch(text, "CDE");
assertEquals(2, index); // Primera ocurrencia de "CDE"
}

@Test
public void testCharactersOutsideExtendedAscii() {
assertEquals(1, BoyerMoore.staticSearch("x中文", "中"));
assertEquals(-1, BoyerMoore.staticSearch("中文", "x"));
assertEquals(2, BoyerMoore.staticSearch("€ €uro", "€uro"));
}
}
Loading