当前代码如下:
public static boolean containsAny(String searchString, List<String> searchCollection) {
int size = searchCollection.size();
for (int i = 0; i < size; i++) {
String stringInCollection = searchCollection.get(i);
if (!Util.isNullOrEmpty(stringInCollection)) {
// This is a performance optimization of contains.
if (searchString.indexOf(stringInCollection, 0) > -1) {
return true;
}
}
}
return false;
}
列表通常有大约30个元素,并且同一集合在每次调用之间经常被重复使用。
上面的代码是一个相当简单的线性搜索。我认为除非我们更改数据结构使其比O(n)更好,否则无法显着改进它。是否有任何数据结构可以让我做到这一点?
Map<Character,List<String>>
,其中键是字母表中的一个字母,而List<String>
包含以该键作为开头的单词的排序列表。或者使用 trie。 - Luiggi Mendoza