【发布时间】:2016-03-16 08:49:09
【问题描述】:
搜索功能有什么问题
search_word();
并且此实现是否使用 Trie 的效率时间复杂度或不用于插入/搜索等操作。 考虑在不到 2 秒的时间内执行插入/搜索操作的 1500 个字母的字符串,可以通过吗?
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);
}
};
更新:发现错误,代码必须正常工作。
【问题讨论】:
标签: c++ string data-structures trie