Trie 查找/添加功能无法正常工作

Trie find/add function not working properly

本文关键字:常工作 工作 查找 添加 功能 Trie      更新时间:2023-10-16

我正在尝试为我的trie树数据结构实现搜索功能。我对如何正确实现这一点感到困惑,因为我认为我的逻辑现在似乎是正确的......虽然我仍然是这方面的初学者。如果有人可以看看我的功能,并建议在哪里改进,那将不胜感激。main接收大型word文件,然后在其中搜索单词以基本测试该功能。现在,它为应该在trie对象中的单词返回false。

示例错误消息

Error: jean-pierre is not in the spellcheck and it should have been

搜索功能:

//looks up the word in the SpellCheck object. If it is in the SpellCheck object,true is returned. 
//You can assume that the word will be all lower case.
bool lookup(const string& word) const {
    if (!root_) {
            return false;
    }
    Node* curr = root_;
    if (word[0] == '') {
            return curr->isTerminal_ == true;
    }

    for (int i = 0; i < word.length(); i++)
    {
            int idx = curr->getIndex(word[i]);
            if (idx < 0 || idx >= 26){
                    return false;
            }
            // Search top level for node that
    // matches first character in key
            if (curr->children_[idx] == nullptr) {
                    return false;
            }
            curr = curr->children_[idx];
    }
    return curr->isTerminal_ == true;
}

节点结构:

struct Node {
            bool isTerminal_;
            char ch_;
            Node* children_[26];
            Node(char c = '') {
                    isTerminal_ = false;
                    ch_ = c;
                    for (int i = 0; i < 26; i++) {
                            children_[i] = nullptr;
                    }
            }
            //given lower case alphabetic charachters ch, returns 
            //the associated index 'a' --> 0, 'b' --> 1...'z' --> 25
            int getIndex(char ch) {
                    return ch - 'a';
            }
    };
    Node* root_;

您的实现中有多个错误。

您的addWord函数不正确。这个应该更好:

void addWord(const string& newWord, int currChar, Node* rt)
{
    //check if currChar index is still in newWord
    if (currChar < newWord.length()) {
        //find index of currChar
        char currLetter = newWord[currChar];
        int idx = rt->getIndex(currLetter);
        //if no letter at that index create a new node
        if (!rt->children_[idx])
            //make a new node
            rt->children_[idx] = new Node(currLetter);
        //continue to add
        addWord(newWord, currChar + 1, rt->children_[idx]);
    }
    else
        rt->isTerminal_ = true; //last char
}

您完全错过的另一个错误:"jean-pierre"包含非 a-z 字符:)并且您的 getIndex 对于不在[a-z]范围内的任何字符都将失败。

其他几点:

  • 不要像26这样的值进行硬编码,因为如果您需要更新您的范围从[a-z]其他地方的代码将以静默失败。
  • 使用断言检查输入假设。

像这样:

int getIndex(char ch)
{
    assert(ch >= 'a' && ch <= 'z');
    return ch == '-' ? 26 : ch - 'a';
}