尝试字典上的数据结构以查找押韵的单词

Trie data structure on dictionary to find rhyming words

本文关键字:查找 单词 数据结构 字典      更新时间:2023-10-16

我正在研究我的函数,该函数将从包含 40,000 个单词的字典文本文件中查找押韵的单词。例如,我输入 akes,它给出打印的单词将是"耙子清酒采取"。所以,我知道它需要具有多个变量的数据结构。也许boolisWord而不是int来说会是一个更好的声明?因此,我显示的功能是修改后的函数,因为原始函数只能打印 1 个与用户输入押韵的单词。因此,我需要在Trie版本中构建数据结构。老实说,我对数据结构很糟糕,所以请耐心等待。

struct Node
{
    char c;
    Node* letters[26];
    bool isWord;
};
bool findWords(Node*& pTail, char dictionary[][MaxLength + 1], int numberOfDictionaryWords)
{
    Node* pHead;
    pHead = pTail->letters[26];
    bool found = false;
    int first = 0;
    int last = numberOfDictionaryWords - 1;
    int middle = (first + last) / 2;
    while (first <= last)
    {
        if (strncmp(pHead, dictionary[middle], strlen(pTail)) > 0)
        {
            first = middle + 1;
        }
        else if (strncmp(pHead, dictionary[middle], strlen(pTail)) == 0)
        {
            char theWord[MaxLength + 1];
            memcpy(theWord, dictionary[middle], sizeof(char) * (MaxLength + 1));
            cout << "Words(s) found: " << strReverse(theWord) << endl;
            found = true;
            break;
        }
        else
        {
            last = middle - 1;
        }
        middle = (first + last) / 2;
    }
    return found;
}

main()

Node* pTail = NULL;
char dictionary[Rows][MaxLength + 1];
int numberOfWords = 0;
readFile(dictionary, numberOfWords);
sortDictionaryInReverse(dictionary, numberOfWords);
char aWord[MaxLength];
cout << "Enter the suffix to find rhyming words: ";
cin >> aWord;
convertToLowerCase(aWord, strlen(aWord));
strReverse(aWord);
if (findWords(aWord, dictionary, numberOfWords))
{
    cout << "This rhyming word is in the dictionary. n";
}
else
{
    cout << "This rhyming word is not in the dictionary. n";
}

我认为std::multimap是你最好的选择。

你的非单词将是键,押韵的单词将是值。

所以你可以像这样设置它:

std::multimap<std::string, std::string> foo;
foo.insert(std::make_pair("akes", "rakes"));
foo.insert(std::make_pair("akes", "sakes"));
foo.insert(std::make_pair("akes", "takes"));

如果你想说打印出"akes"的所有押韵,你可以这样做:

std::cout << "akesnt";
for(auto i = foo.equal_range("akes"); i.first != i.second; ++i.first){
    std::cout << i.first->second << ' ';
}

如果你只想打印出第一个元素,你可以这样做:

std::cout << "akes " << foo.find("akes")->second;