将一组字符串与一个字符串进行比较的最快方法是什么?

What is the fastest way to compare set of strings to one string?

本文关键字:字符串 是什么 比较 方法 一个 一组      更新时间:2023-10-16

我有一组字符串,我需要找到一个特定的字符串是否在其中。我只需要这样做一次(下次字符串不同)。

我想用桶排序排序字符串,然后做二进制搜索。

时间复杂度:O(n+k)+O(log n)

有更快/更好的解决方案吗?

这里的set指的是更多的字符串,而不是std::set。

将以上评论总结为一个答案。如果你正在加载要动态比较的字符串,并且不需要它们按照特定的顺序排列,那么std::unordered_set是目前为止最快的。

unordered_set是一个哈希集,它将通过哈希函数输入字符串,并查找它是否已经在常数时间O(1)中存在。

如果你需要保留元素的顺序,那么问题就变成了保留一个向量并通过它进行线性搜索更快,或者是否仍然值得构建哈希集。

代码:

std::unordered_set<std::string> theSet;
// Insert a few elements.
theSet.insert("Mango");
theSet.insert("Grapes");
theSet.insert("Bananas");
if ( theSet.find("Hobgoblins") == theSet.end() ) {
    cout << "Could not find any hobgoblins in the set." << endl;
} 
if ( theSet.find("Bananas") != theSet.end() ) {
    cout << "But we did find bananas!!! YAY!" << endl;
}
比较:

如果你使用std::vector,你将需要O(n)时间构建向量,然后O(n)时间找到一个元素。

如果您使用std::unordered_set,您仍然需要O(n)时间来构建向量,但之后您可以在常数时间O(1)中找到元素。