Trie 查找/添加功能无法正常工作
Trie find/add function not working properly
我正在尝试为我的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';
}
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 为什么STD ::计数将常数传递给Lambda,而不是在弦上工作时而不是字符
- C++程序已停止工作-求解常微分方程