Skip to content

Commit 7643e24

Browse files
fix(searches): support characters outside extended ASCII in BoyerMoore (#7664)
1 parent 410f087 commit 7643e24

2 files changed

Lines changed: 15 additions & 10 deletions

File tree

‎src/main/java/com/thealgorithms/searches/BoyerMoore.java‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,25 @@
11
package com.thealgorithms.searches;
22

3+
import java.util.HashMap;
4+
import java.util.Map;
5+
36
/**
47
* Boyer-Moore string search algorithm.
58
* Efficient algorithm for substring search.
69
* https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm
710
*/
811
public class BoyerMoore {
912

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

1416
public BoyerMoore(String pat) {
1517
this.pattern = pat;
16-
this.radix = 256;
17-
this.right = new int[radix];
18-
19-
for (int c = 0; c < radix; c++) {
20-
right[c] = -1;
21-
}
18+
// A map instead of a 256-entry array, so characters outside extended ASCII work too
19+
this.right = new HashMap<>();
2220

2321
for (int j = 0; j < pat.length(); j++) {
24-
right[pat.charAt(j)] = j;
22+
right.put(pat.charAt(j), j);
2523
}
2624
}
2725

@@ -40,7 +38,7 @@ public int search(String text) {
4038
char txtChar = text.charAt(i + j);
4139
char patChar = pattern.charAt(j);
4240
if (patChar != txtChar) {
43-
skip = Math.max(1, j - right[txtChar]);
41+
skip = Math.max(1, j - right.getOrDefault(txtChar, -1));
4442
break;
4543
}
4644
}

‎src/test/java/com/thealgorithms/searches/BoyerMooreTest.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,11 @@ public void testStaticSearchMethod() {
5252
int index = BoyerMoore.staticSearch(text, "CDE");
5353
assertEquals(2, index); // Primera ocurrencia de "CDE"
5454
}
55+
56+
@Test
57+
public void testCharactersOutsideExtendedAscii() {
58+
assertEquals(1, BoyerMoore.staticSearch("x中文", "中"));
59+
assertEquals(-1, BoyerMoore.staticSearch("中文", "x"));
60+
assertEquals(2, BoyerMoore.staticSearch("€ €uro", "€uro"));
61+
}
5562
}

0 commit comments

Comments
 (0)