Java的Boyer Moore算法:如何向后查找位置?

时间:2019-01-17 16:26:41

标签: java data-structures boyer-moore

我正在尝试使用java实现Boyer Moore算法的不同方法,在完成上一个实现后,我只是想这样做,但是这次我想向后搜索。像这样: haystack =“ abcdef”,needle =“ bc”,其中needle从右向左移动以完成搜索。 我知道我需要改变几个方向,但似乎可以正确解决。

有帮助吗? 预先感谢

这是我的代码。

private int comparisonCount;
int seekLocation(String needle, String haystack) {
    int[] lastOcc;
    int i, j, needleLength, haystackLength;

    String N = needle.toLowerCase();
    String H = haystack.toLowerCase();

    haystackLength = H.length();
    needleLength = N.length();

    lastOcc = computeLastOcc(needle);

    i = 0;
    while (i < (haystackLength - needleLength)) {

        j = needleLength - 1;
        while (N.charAt(j) == H.charAt(i + j)) {
            j--;
            if (j < 0) {
                return (i);
            }
        }
        if (j < lastOcc[H.charAt(i + j)]) {
            i++;
        } else {
            i = i + j - lastOcc[H.charAt(i + j)];
        }
    }
    return -1;
}

public int[] computeLastOcc(String needle) {
    int[] lastOcc = new int[256];

    for (int i = 0; i < lastOcc.length; i++) {
        lastOcc[i] = -1; 
    }

    for (int i = 0; i < needle.length(); i++) {
        lastOcc[needle.charAt(i)] = i; 
    }
    return lastOcc;
}

/**
 * Returns the number of character compares that where performed during the
 * last search.
 *
 * @return the number of character comparisons during the last search.
 */
int getComparisonsForLastSearch() {
    return this.comparisonCount;
}

public static void main(String[] args) {
    BackwardsSearch bws = new BackwardsSearch();
    int find = bws.seekLocation("de", "abcde");
    System.out.println("Location : " + find);
    int totaalComparison = bws.getComparisonsForLastSearch();
    System.out.println("Comparison : " + totaalComparison);
}

0 个答案:

没有答案