【发布时间】:2014-04-03 15:28:31
【问题描述】:
我一直在尝试使用 java 的二进制搜索方法在单词数组(词典)中搜索特定字符串,然后确定该字符串是单词、前缀还是不是单词。如果返回的索引大于或等于零,则字符串是一个单词。如果返回的索引小于零,那么我必须确定它是不是单词,还是前缀。
例如,例如,当查找“ela”时,返回的值可能是 -137。这意味着“ela”不在词典中,但如果要插入它,它将在索引 136 处。这也意味着如果索引 136 处的单词不以“ela”开头,则词典中没有单词“ela”的前缀。因此,binarySearch 返回的任何非负值都意味着单词的状态是 LexStatus.WORD。如果返回的值为负数,则调用适当的 String.startsWith() 方法可以确定是否应返回 LexStatus.PREFIX(确保在调用startsWith 时不要超出词典中单词数组的末尾) .
到目前为止,我编写的代码如下所示。我通过了 .isWord() 和 .isNotWord() 的 J 单元测试;但是我没有通过 .isPrefix() 测试,我目前将前缀标记为非单词。你们能帮我找出我的错误吗?
public LexStatus wordStatus(String s) {
String [] myWordsArray = new String[myWords.size()];
myWords.toArray(myWordsArray);
int wordIndex= Arrays.binarySearch(myWordsArray,s);
if(wordIndex>=0){
return LexStatus.WORD;
}
else{
int checkIndex = (wordIndex*-1)+1;
if(checkIndex<=myWords.size()-1){
String precedingWord= myWords.get(checkIndex);
String check1=precedingWord.toLowerCase();
String check2= s.toLowerCase();
if(check1.startsWith(check2)){
return LexStatus.PREFIX;
}
return LexStatus.NOT_WORD;
}
return LexStatus.NOT_WORD;
}
}
【问题讨论】:
-
wordIndex*-1写-wordIndex的路很长 -
有人没有做作业...APCS?
-
能否详细说明?
标签: java binary-search