java - 当单词不存在时,递归二进制搜索返回 stackoverflow 错误
问题描述
我写了一个递归二进制搜索方法,如果字典中存在这个词,它就可以工作,但是,当我输入一个不存在的词时,比如“rwetjia”,我得到一个stackoverflow错误
public boolean wordCheck(String target, int start, int end) {
target.toLowerCase();
if (end >= 1) {
int middle = start + (end - start) / 2;
int targetside = target.compareTo(words.get(middle));// Finds which side the word is on
if (targetside == 0) {
return true;
} // Word is at the middle (the word exists and has been found)
else if (targetside > 0) {
return wordCheck(target, middle + 1, end);
} // If target word is on the right side of the array, "cuts" the other half off
else {
return wordCheck(target, start, middle - 1);
}
} // If target word is on the left side of the array, "cuts" the other half off
return false; // Word is not in the dictionary
}
解决方案
尝试:
if (end >= start) {
代替
if (end >= 1) {
更新:
我假设这end
是要考虑的最后一个元素的索引(请参阅我上面的评论);否则,测试将是:
if (end > start) {
你需要更换:
return wordCheck(target, start, middle - 1);
和:
return wordCheck(target, start, middle);
推荐阅读
- python - 用于最小二乘 kabsch 算法的 SCIPY 库示例 align_vectors
- c - 创建用户名函数如果根本没有输入怎么办?
- c# - 在 .NET Core Docker 映像中包含共享 C 库 (.SO)
- c# - 如何使用 Speex 正确移除回声消除?
- angular - Angular 库模块注入抽象类的相同服务实例
- postgresql - PostgreSQL:全文搜索未按预期工作
- css - 使用 opentypejs 仅显示特定字形
- vue.js - Vuelidate $each:如何验证嵌套集合?
- flutter - 为什么 BlocProvider.value 仅在我将变量转换为它自己的类型时才有效?
- python - 在 python 中使用 wget / urllib / requests 下载图像 HTTP 403 EROR