For an school assignment, we are implementing suffixarray, with the methods of building it and finding the longest common prefix. I manage to build and sort the suffix array quite easily but struggle with the LCP.
I am trying to find the longest common prefix of a pattern string P in another string T, using one singular binary search. The algorithm should return the index of where the longest common prefix begins.
Examples:
- If the pattern string P is "racad" and the string T is "abracadabra", the longest common prefix should be "racad", beginning at index 2.
Likewise, if the the pattern string is P "rax" then the longest common prefix should be "ra", beginning at index 2 or 9.
I´ve come quite far but the algorithm is not returning the right value. Here´s my code:
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; }
I run it with this main-method:
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));
}
The output is always whatever value I initialize the local variable left
with.
The search algorithm must do a singular binary search. I´ve tried searching other stackoverflow-questions and other web-sources but have not found anything helpfull.
Anyone who can see any errors in my code?