对于学校作业,我们正在实现 suffixarray,使用构建它的方法并找到最长的公共前缀。我设法很容易地构建和排序后缀数组,但在 LCP 上遇到了困难。
我正在尝试使用一个奇异的二进制搜索在另一个字符串 T 中找到模式字符串 P 的最长公共前缀。该算法应该返回最长公共前缀开始的索引。
例子:
- 如果模式字符串 P 是“racad”并且字符串 T 是“abracadabra”,那么最长的公共前缀应该是“racad”,从索引 2 开始。
同样,如果模式字符串是 P“rax”,那么最长的公共前缀应该是“ra”,从索引 2 或 9 开始。
我已经走了很远,但算法没有返回正确的值。这是我的代码:
public int compareWithSuffix(int i, String pattern) { int c = 0; int j = 0; while (j < pattern.length() && c == 0) { if (i + j <= text.length()) { c = pattern.charAt(0 + j) - text.charAt(i + j); } else { c = 1; } j++; } return c; } public int binarySearch(String pattern) { int left = 0; int right = text.length() - 1; int mid, c = 0; while (c != 0 && left <= right) { mid = left + (right - left) / 2; c = compareWithSuffix(mid, pattern); if (c < 0) { right = mid - 1; } else if (c > 0) { left = mid + 1; } else if (c == 0) { return mid; } } return left; }
我用这个主要方法运行它:
public static void main(String[] args) {
String word = "abracadabra";
String prefix1 = "rax";
String prefix2 = "racad";
SuffixArray s = new SuffixArray(word);
System.out.println("Longest common prefix of: " + "'" + prefix1 + "'" + " in " + "'" + word + "'" + " begins at index: " + s.binarySearch(prefix1));
System.out.println("Longest common prefix of: " + "'" + prefix2 + "'" + " in " + "'" + word + "'" + " begins at index: " + s.binarySearch(prefix2));
}
输出始终是我初始化局部变量的任何值left
。
搜索算法必须进行奇异二分搜索。我试过搜索其他 stackoverflow-questions 和其他网络资源,但没有发现任何有用的东西。
谁能在我的代码中看到任何错误?