Câu hỏi phỏng vấn Java
Câu hỏi

Explain Boyer-Moore Algor...

Câu trả lời

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.

Key Features of Boyer-Moore Algorithm

  1. Right to Left Scanning: Unlike traditional search algorithms that scan the text from left to right, Boyer-Moore starts matching from the rightmost character of the pattern.
  2. Bad Character Heuristic: This heuristic shifts the pattern more intelligently by aligning the text character that caused the mismatch with its last occurrence in the pattern.
  3. Good Suffix Heuristic: When a substring of the pattern has been matched, but a mismatch occurs at a preceding character, this heuristic shifts the pattern to align with another occurrence of the matched substring if possible.

Java Implementation Example

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

senior

Gợi ý câu hỏi phỏng vấn

senior

What are the differences between a HashMap and a HashTable in Java?

expert

Compare volatile vs static variables in Java

junior

What is JDBC?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào