搜索功能有什么问题
search_word();
这个实现是否使用 Trie 的效率时间复杂度或不用于插入/搜索等操作。 考虑一个 1500 个字母的字符串在小于 2 秒的时间内执行插入/搜索操作,它可以通过吗?
class Trie
{
private:
struct node
{
bool isWord;
node* child[26];
node()
{
for(int i = 0;i < 26;i++)
child[i] = NULL;
isWord = false;
}
};
void insert_word(int index, node* vertex, int i, string s)
{
if(index == SZ)
{
vertex -> isWord = true;
return;
}
int c = s[index] - 'a';
if(vertex -> child[c] == NULL)
vertex -> child[c] = new node;
insert_word(index + 1, vertex -> child[c], c, s);
}
bool search_word(int index, node* vertex, int i, string s)
{
if(index == SZ && vertex -> isWord == true)
return true;
if(index == SZ && vertex -> isWord == false)
return false;
int c = s[index] - 'a';
if(vertex -> child[c] == NULL)
return false;
else
return search_word(index + 1, vertex -> child[c], c, s);
}
public:
int SZ;
node* root;
Trie()
{
root = new node;
}
void insert_word(string s)
{
SZ = s.size();
insert_word(0, root, s[0] - 'a', s);
}
bool search_word(string s)
{
SZ = s.size();
return search_word(0, root, s[0] - 'a', s);
}
};
更新:发现错误,代码必须正常工作。
最佳答案
好吧,我已经找到了错误,它在代码块中
if(index == (SZ - 1))
{
vertex -> isWord = true;
return;
}
索引必须检查 == 大小本身不是 size-1 为什么..? 例如:字符串 ab 如果我们现在在字母 b 处处理,它是否 == 到 size - 1 表示字符串中的最后一个字符,代码将其根标记为单词结尾而不是与字符 b 相关的节点,因为它从未存在过创建 通过编辑它的大小,它也应该在
中正常工作search_word()
尺寸 - 1 也必须编辑
注意:我将更新问题本身以获得固定代码。
关于c++ - Trie 数据结构实现的 bug,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34206616/