【发布时间】:2022-01-01 04:48:08
【问题描述】:
我有一个std::vector<std::string>,它有 43,000 个字典单词。我有大约 315,000 个可能的单词,对于每个单词,我都需要确定它是否是一个有效的单词。这需要几秒钟,我需要尽快完成任务。
关于完成此任务的最佳方法有什么想法吗?目前我在每次尝试中都进行迭代:
for (std::string word : words) {
if (!(std::find(dictionary.begin(), dictionary.end(), word) != dictionary.end())) {
// The word is not the dictionary
return false;
}
}
return true;
有没有更好的方法进行多次迭代?我有几个假设,比如
- 创建一个无效词的缓存,因为 315,000 个列表可能有 25% 的重复项
- 只比较相同长度的单词
有没有更好的方法来做到这一点?我对算法或想法感兴趣。
【问题讨论】:
-
也许您想使用
std::set<std::string>或std::unordered_set<std::string>而不是向量。 -
将值放在
std::unordered_set<std::string>中,然后它们将是唯一的,并且平均有 O(1) 查找。 -
可能应该使用
set或unordered_set而不是vector。 -
你能对你的
vector(用于二分搜索)进行排序吗?或者使用另一个容器(std::unordered_set、trie、...) -
你可以使用排序
std::vector吗?在已排序的 std::vector 中进行二分搜索可能会有很好的性能。更好的是对它们中的 both 进行排序,然后遍历这两个向量,并在通过两个排序列表的某种智能单次迭代中将可能的词标记为好或坏。
标签: c++ loops dictionary