这里我有一个英语单词表:(例如)
account
angel
apple
application
black
...
我想搜索以特定字符串开头的字符串。例如:“ap”的结果应该是 { apple, application }。
可以通过基于序列搜索的解决方案轻松实现返回一组相应的字符串。但仍然有比序列搜索更强的算法,但它们只返回一个字符串。那么,有什么理想的方法可以比基于序列搜索的方法更快地从 ArrayList 返回一组相应的字符串吗?
谢谢!
最佳答案
标准 API 已经有 binary search这样就可以做到这一点:
int index = Collections.binarySearch(list, key);
if (index < 0) {
index = -(index + 1);
}
List<String> result = new ArrayList<String>();
while (index < list.size()) {
String s = list.get(index);
if (s.startsWith(key)) {
result.add(s);
}
else {
break;
}
index++;
}
关于java - 从java中排序的ArrayList中的特定字符串开始搜索字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21113114/