将一组字符串与一个字符串进行比较的最快方法是什么?
What is the fastest way to compare set of strings to one string?
我有一组字符串,我需要找到一个特定的字符串是否在其中。我只需要这样做一次(下次字符串不同)。
我想用桶排序排序字符串,然后做二进制搜索。
时间复杂度: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)中找到元素。
相关文章:
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 在C++17中,引用const字符串的语义应该是什么
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 字符串上的 C++ push_back() 和 pop_back() 的 Kotlin 是什么?
- 这里的字符串函数是什么意思
- 将位字符串转储到二进制文件的最佳方法是什么
- 是什么使这个以'+'开头的字符串添加成为有效的语句?
- 在c++中,减号和加号对字符串的作用是什么
- 当我们已经有 char[] 时,在 c++ 中字符串的必要性是什么?
- C++ 将字符串数据包转换为 iphdr语言 - 字符串数据包的格式应该是什么?
- 这句话是什么意思?半 += 字符串(频率[i] / 2, i + 'a');
- Xamarin Android:在 C++ 中将字符串从 C# 封送到 Unicode 字符串的正确方法是什么?
- 使用c 中的sort()函数对字符串进行排序的最坏情况是什么是什么
- 字符串文本不能有外部链接的原因是什么?
- 当我打印字符串时,我不知道它是什么输出
- 字符串中单个字符作为数组的数据类型是什么
- 检查字符串是否与可能的输入之一匹配的最有效方法是什么?
- '|' scanf 格式字符串是什么意思
- 一个字符串开始另一个字符串是什么意思?c++
- 表示文件路径的guid字符串是什么?