c++ - 有没有办法使用有限的字母范围搜索 unordered_set?
问题描述
上下文:我正在用 C++ 编写一个作业,用户输入一个单词或一个句子以逐字解读。我有一个充满英语单词的文本文件,我已将其读入 unordered_set 字符串。然后我检查每个输入单词的排列并尝试在 unordered_set 中找到它。未加扰的单词可能性被打印给用户。
问题:文本文件中有很多单词。该程序无法正常运行,因为遍历所有排列并在 unordered_set 中寻找匹配项需要很长时间。
可能的解决方案:我想限制要搜索的单词范围,因为文本文件已经按字母顺序排列。例如,如果加扰的词是“cit”,那么这个词的一个排列是“itc”。我想在 unordered_set 中以 i 开头的所有单词搜索“itc”。
这是我到目前为止所拥有的。
void unscramble() {
//issue - too slow, find in range?
string word;
string temp;
ifstream inDictionaryFile("words_alpha.txt");
unordered_set<string> dictionary;
//read dictionary file into a unordered_set
while (getline(inDictionaryFile, temp)) {
auto result = dictionary.insert(temp + " ");
}
cout << "Enter something to unscramble: ";
//find/print out matches for permuations of scrambled words
while (cin>>word) {
do {
word = word + " ";
auto result = dictionary.find(word);
if (result != end(dictionary)) {
cout << setw(10) << word;
}
} while (next_permutation(begin(word), end(word)));
}
}
解决方案
如果您只需要前 3 个字母的排列,您可以使用 unordered_multiset,其键等于规范排列(例如,排序的前 3 个字母)。但我想你的实际问题不应该只用一个数据结构来解决,而是用几个数据结构来解决,一个数据结构用于存储,其他数据结构用于该存储的索引。
推荐阅读
- webrtc - 我们如何让 WebRTC 与 VPN 一起工作(已尝试 TURN 解决方案)
- c++ - 如何调试 atan2 中的段错误?
- cryptography - 如果自定义 CSP dll 依赖于另一个自定义 dll,为什么它不被 Adobe Reader 或 Word 等应用程序接受?
- reactjs - 在 Jest 中模拟 WithRouter
- javascript - 使用 jQuery 以毫秒计算两次时间
- regex - 如果 a a1 匹配 B:B 中的任何单元格,则 C
- google-cloud-storage - Google Cloud API Gateway 端点如何从 Cloud Storage 文件传送数据?
- typescript - 我的项目有 tsx 和 ts 文件,但我想在测试文件中禁用 ts
- python - 使用余弦核的 SVM - 带有狗和猫图像的数据集
- java - 在 Java 中输入命令行参数后,如何创建代码以使 c^2 = a^2 + b^2 中的 c 成为最长边?