搜索功能中的错误是什么
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);
}
};更新:发现了错误,代码必须正常工作。
发布于 2015-12-13 05:41:14
好了,我已经找到了这个bug,它在代码块中
if(index == (SZ - 1))
{
vertex -> isWord = true;
return;
}必须检查具有大小本身而不是大小的==的索引。?例如: string ab如果我们现在在字母b处处理,那么它的大小是否为== -1,这意味着字符串中的最后一个字符,代码将把它的词根标记为单词的结尾,而不是与字符b相关的节点,因为它从来没有通过编辑它来创建它的大小,它应该也可以在
search_word()size -1也必须编辑
注意:我将更新问题本身,使其具有固定的代码。
https://stackoverflow.com/questions/34206616
复制相似问题