Explain Boyer-Moore Algor...
Explain Boyer-Moore Algor...
The Boyer-Moore algorithm is a highly efficient string searching (or matching) algorithm that is particularly effective when the pattern to be searched is shorter than the text in which it is searched. It was developed by Robert S. Boyer and J Strother Moore in 1977. The algorithm preprocesses the pattern to create various tables, which are then used to skip sections of the text, thereby reducing the number of comparisons typically needed in simpler search algorithms like the naive string search.
Here is a simple Java implementation of the Boyer-Moore algorithm focusing on the Bad Character Heuristic:
public class BoyerMoore {
private final int R; // the radix
private int[] right; // the bad-character skip array
private char[] pattern; // store the pattern as a character array
private String pat; // or as a string
// Preprocesses the pattern string.
public BoyerMoore(String pat) {
this.R = 256;
this.pat = pat;
pattern = pat.toCharArray();
right = new int[R];
for (int c = 0; c < R; c++)
right[c] = -1;
for (int j = 0; j < pattern.length; j++)
right[pattern[j]] = j;
}
// Returns the index of the first occurrence of the pattern string
// in the text string.
public int search(String txt) {
int m = pattern.length;
int n = txt.length();
int skip;
for (int i = 0; i <= n - m; i += skip) {
skip = 0;
for (int j = m-1; j >= 0; j--) {
if (pattern[j] != txt.charAt(i+j)) {
skip = Math.max(1, j - right[txt.charAt(i+j)]);
break;
}
}
if (skip == 0) re...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào