有没有一种方法可以使用有限的字母范围来搜索一个无序的_集?

问题描述 投票:0回答:1

上下文。我正在用C++编写一个任务,让用户输入一个单词或一个句子,以逐个单词进行解读。我有一个充满英文单词的文本文件,我把这些单词读成一个无序的字符串集。然后,我对每个输入的单词进行排列组合,并试图在无序集合中找到它。未排序的单词可能性被打印出来给用户。

问题:文本文件中有很多单词。程序无法正常运行,因为它需要花费太长的时间来检查所有的排列组合,并在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)));
    }


}

c++ string search
1个回答
0
投票

如果你只需要前3个字母的排列组合,你可以使用一个unordered_multiset,其键等于一个规范的排列组合(例如排序的前3个字母)。但我想,你所遇到的实际问题不应该只用一个数据结构来解决,而应该用多个数据结构来解决,一个数据结构用于存储,其他数据结构用于该存储的索引。

© www.soinside.com 2019 - 2024. All rights reserved.