-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathProblem_25.java
More file actions
59 lines (44 loc) · 1.84 KB
/
Problem_25.java
File metadata and controls
59 lines (44 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package strings;
//* Boyer Moore Algorithm for Pattern Searching.
public class Problem_25 {
public static int search(String text, String pattern) {
int n = text.length();
int m = pattern.length();
// Preprocessing: create bad character table
int[] badCharTable = buildBadCharTable(pattern);
int shift = m - 1; // Initial shift
while (shift <= n - m) {
int j = m - 1; // Index for pattern
while (j >= 0 && text.charAt(shift + j) == pattern.charAt(j)) {
j--; // Characters match, move to previous character
}
if (j == -1) { // Pattern found
return shift;
}
// Mismatch occurred, use bad character table
shift += Math.max(badCharTable[text.charAt(shift + j)] - j, 1);
}
return -1; // Pattern not found
}
private static int[] buildBadCharTable(String pattern) {
int[] badCharTable = new int[256]; // Assuming ASCII characters
// Fill the table with the maximum distance between the current character
// and its rightmost occurrence in the pattern (except the last character)
for (int i = 0; i < pattern.length() - 1; i++) {
badCharTable[pattern.charAt(i)] = pattern.length() - 1 - i;
}
// The last character of the pattern always gets a shift of 1
badCharTable[pattern.charAt(pattern.length() - 1)] = 1;
return badCharTable;
}
public static void main(String[] args) {
String text = "THIS IS A TEXT BOOK EXAMPLE";
String pattern = "EXAMPLE";
int index = search(text, pattern);
if (index != -1) {
System.out.println("Pattern found at index: " + index);
} else {
System.out.println("Pattern not found in the text.");
}
}
}