我的代码正确计算了intervall的起始位置,但没有计算结束位置:
int left;
int bot = 0; int top = textLength;
while(bot != top)
{
int mid = (bot+top)/2;
if(pattern.compareTo(text.substring(suffixArray.get(mid))) > 0) bot = mid + 1;
else top = mid;
}
left = bot;
int right;
bot = left; top = textLength;
while(bot != top)
{
int mid = (bot+top)/2;
if(pattern.compareTo(text.substring(suffixArray.get(mid))) < 0) top = mid;
else bot = mid+1;
}
right = bot;
我将它与互联网上的几个伪代码进行了比较,我不明白为什么它不起作用。我错过了什么?
答案 0 :(得分:1)
right
的搜索仅在>=
而非>
if(pattern.compareTo(text.substring(suffixArray.get(mid))) >= 0) bot = mid + 1;
else top = mid;
所以我会想到
right = bot;
指向下一个更高的值。
所以最好先检查一下是否全部订购:
String old = text.substring(suffixArray.get(0));
for (int i = 1; i < textLength; ++i) {
String next = text.substring(suffixArray.get(i));
if (old.compareTo(next) >= 0) {
System.err.printf("Wrong order at [%d] '%s' >= [%d] '%s'%n",
i - 1, old, i, next);
}
old = next;
}