【问题标题】:What is the fastest way to compare set of strings to one string?将一组字符串与一个字符串进行比较的最快方法是什么?
【发布时间】:2014-09-03 06:31:11
【问题描述】:

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

我正在考虑用桶排序对字符串进行排序,然后进行二进制搜索。

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

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

对于 set,我的意思是更多的字符串,而不是 std::set。

【问题讨论】:

  • std::find 是 O(n)。除非你指的是实际的std::set,在这种情况下它有一个find 成员函数。
  • std::set::find 是 O(log(n))
  • 如果你只做一次,你不妨单独比较每个字符串。
  • std::unordered_set::find 是 O(1) :p
  • @quantdev - 在集合构建之后。搭建一套需要多少钱?

标签: c++ string sorting time compare


【解决方案1】:

在一个答案中总结上面的 cmets。如果您正在加载要动态比较的字符串并且不需要它们按特定顺序排列,那么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) 时间内找到一个元素。

【讨论】:

  • 当有两个字符串匹配搜索字符串时,unordered_set 如何工作?我需要知道有两个字符串,哪个是。
  • @user3437139 实际上,unordered_set 不会发生这种情况。容器的限制之一是它最多可以包含给定值的一个副本。为了查找重复项,您可以考虑使用允许重复项的 unordered_multiset。或者您可以查看使用 unordered_map 其中 int 是每个字符串的出现次数。我推荐后者。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多