【问题标题】:Trie only inserting first letter of a word, not the whole word尝试只插入单词的第一个字母,而不是整个单词
【发布时间】:2019-04-02 22:36:47
【问题描述】:

我目前正在开发一个程序,我正在将单词插入到 trie 中。目前我的插入功能只添加单词的第一个字母然后停止。从我查找的所有内容来看,我的代码看起来是正确的,所以我不明白问题是什么。

我尝试将 temp-> wordEnd = true 移到 for 循环的外部和函数的不同位置。因为我相信这是问题所在,因为我的插入函数中的所有其他内容看起来都是正确的。

这是我的插入函数:

bool Trie::insert(string word)
{
    TrieNode *temp = root;
    temp->prefixAmount++;

    for (int i = 0; i < word.length(); ++i)
    {
        int currentLetter = (int)word[i] - (int)'a';
        if (temp->child[currentLetter] == NULL)
        {
            temp->child[currentLetter] = new TrieNode();
            temp->child[currentLetter]->prefixAmount++;
            temp = temp->child[currentLetter];
        }
        temp->wordEnd = true;
        return true;
    }
}

也帮助大家更好地遵循我的代码 这是我的 TrieNode 结构:

  struct TrieNode
   {
     int prefixAmount;
     struct TrieNode *child[ALPHA_SIZE];
    bool wordEnd;

   };

这是我的 Trie 构造函数:

   Trie::Trie()
    {
      root = new TrieNode();
      root->wordEnd = false;
     root->prefixAmount = 0;

     }

预期的结果应该是插入了整个单词。 实际发生的是只添加了单词的第一个字母。

【问题讨论】:

    标签: c++ insert trie


    【解决方案1】:

    我已经为你重新格式化了代码,现在你应该可以看到主要问题了。

    您将在 for 循环内的块末尾返回。这意味着它会运行 for 循环的第一次迭代,然后直接返回而不考虑其余字母。

    一个简单的解决方法是将 return 放在 for 循环之外,但是如果当前字母已经在其中,则还有另一个问题是您无法正确更新 Trie。你的NULL 检查是正确的,但你应该只在NULL 上的TrieNode 上运行new,但你也想运行所有后续行,即使它不是NULL。固定代码如下所示:

    bool Trie::insert(string word)
    {
        TrieNode *temp = root;
        temp->prefixAmount++;
    
        for (int i = 0; i < word.length(); ++i)
        {
            int currentLetter = (int)word[i] - (int)'a';
            if (temp->child[currentLetter] == NULL)
            {
                temp->child[currentLetter] = new TrieNode();
            }
            temp->child[currentLetter]->prefixAmount++;
            temp = temp->child[currentLetter];
        }
        temp->wordEnd = true;
        return true;
    }
    

    (代码中超出问题范围的其他小问题 - 更喜欢 nullptrNULL,如果它总是 true,为什么返回 bool,如果您的字符串包含 a-z 之外的任何内容,那么您将在数组边界之外阅读,更喜欢 unique_ptrmake_unqiue 而不是原始 new/delete)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多