【问题标题】:Trie data structure on dictionary to find rhyming words尝试字典上的数据结构以查找押韵单词
【发布时间】:2014-11-26 01:55:15
【问题描述】:

我正在开发我的函数,该函数将从包含 40,000 个单词的字典文本文件中查找押韵单词。例如,我输入 akes,它给出的打印词是“rakesakestakes”。所以,我知道它需要具有多个变量的数据结构。也许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";
}

【问题讨论】:

  • 处理器处理int 的速度通常与bool 一样快。您只能使用bool 进行打包,这会减慢执行速度。您是否分析过您的代码以找出瓶颈所在?
  • 我建议您使用不同的数据结构,更适合您的目的。例如,您可以有一个包含 26 个列表或树的数组,每个字母对应一个。这将减少您对 O(1) 的首次访问,因为您可以使用该字母来索引数组;不涉及搜索。

标签: c++ dictionary data-structures trie


【解决方案1】:

我认为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 << "akes\n\t";
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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多