我正在尝试为我的trie树数据结构实现搜索功能。我对如何正确实现这一点感到困惑,因为我认为我的逻辑现在看起来是正确的......尽管我仍然是这方面的初学者。如果有人可以看看我的功能,并建议在哪里进行改进,那将非常感激。主要接受大型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] == '\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 = '\0') {
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_;
答案 0 :(得分:0)
您的实施中存在多个错误。
您的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字符:)并且对于任何不在[a-z]
范围内的字符,您的getIndex将失败。
其他要点:
26
之类的值进行硬编码,因为如果您需要更新您的
范围从其他地方的[a-z]
代码将无声地失败。这样的事情:
int getIndex(char ch)
{
assert(ch >= 'a' && ch <= 'z');
return ch == '-' ? 26 : ch - 'a';
}