Как я могу найти наиболее подходящее совпадение с помощью алгоритма Бойера Мура?

Мне нужно внедрить Boyer Moore, но он должен найти наиболее подходящее для этого случая. (Так что обратная версия Бойера Мура). Возвращает индекс самого правого места в тексте, где встречаются шаблоны. Поиск * начинается с правой стороны текста и продолжается до первого символа (слева). Я попытался отменить циклы for и подсчитать количество повторов, но мой код по-прежнему не работает должным образом. Я думаю, что это не так, но я не уверен. Это мой код:

public class BoyerMoore {
private final int R;     // the radix
private int[] right;     // the bad-character skip array
private int ocurrences;

/**
 * Preprocesses the pattern string.
 *
 * @param pat the pattern string
 */
public BoyerMoore(String pat) {
    this.R = 256;
    // position of rightmost occurrence of c in the pattern
    right = new int[R];
    for (int c = 0; c < R; c++)
        right[c] = -1;
    for (int j = 0; j < pat.length(); j++)
        right[pat.charAt(j)] = j;
}

/**
 * Returns the index of the first occurrrence of the pattern string
 * in the text string.
 *
 * @param  txt the text string
 * @return the index of the first occurrence of the pattern string
 *         in the text string; n if no such match
 */
public int search(String txt, String pat) {
    int m = pat.length();
    int n = txt.length();
    int skip;
    for (int i = n - m; i >= 0; i -= skip) {
        skip = 0;
        for (int j = 0; j < n; j++) {
            ocurrences++;
            if (pat.charAt(j) != txt.charAt(i+j)) {
                skip = Math.max(1, j - right[txt.charAt(i+j)]);  //Kijk naar die char
                break;
            }
        }
        if (skip == 0) return i;    // found
    }
    return n;                       // not found
}


int getComparisonsForLastSearch() {
    return ocurrences;
}

}

0 ответов

Другие вопросы по тегам