Trie前缀树是我之前在学数据结构的时候看到的一个树型结构,但是我从来没有用过,也没有具体实现过,这次刷力扣刷到了这题,就凭记忆实现了一下。
题目:
首先看看前缀树的结构:
从根节点开始会根据对应的字母(abcd)去查找下一个节点。
当我们到了一个单词结尾的时候会标记这个节点,表示从头开始到当前这个节点是一个单词。
回到题目:
我们需要实现的是:1.字典树节点结构。2.插入功能,3.单词查询,4.前缀查询。
1.字典树节点结构
字典树的节点结构我采用链式+map的方式实现,每个字符映射一个节点,用布尔标记是否是一个完整单词。
struct Node
{
map<char,Node*> next;
bool f=false;
};
2.插入功能
插入的时候我们从头节点开始查询是否存在目标字符到目标节点的映射,如果不存在我们需要创建新节点。并且在最后一个目标字符的时候设置标记。
void insert(string word) {
Node * t=head;
for(char c:word)
{
if(t->next[c]==NULL)
{
Node* n=new Node;
t->next[c]=n;
}
t=t->next[c];
}
t->f=true;
}
3.两种查询功能
查询的时候我们就根据目标字符和对应节点的映射遍历,如果是查询单词遍历到最后,需要检查标记。
bool search(string word) {
Node * t=head;
for(char c:word)
{
if(t->next[c]==NULL)
{
return false;
}
t=t->next[c];
}
return t->f;
}
bool startsWith(string prefix) {
Node * t=head;
for(char c:prefix)
{
if(t->next[c]==NULL)
{
return false;
}
t=t->next[c];
}
return true;
}
最后是整体AC代码:
struct Node
{
map<char,Node*> next;
bool f=false;
};
class Trie {
public:
Node * head;
/** Initialize your data structure here. */
Trie() {
head=new Node();
}
/** Inserts a word into the trie. */
void insert(string word) {
Node * t=head;
for(char c:word)
{
if(t->next[c]==NULL)
{
Node* n=new Node;
t->next[c]=n;
}
t=t->next[c];
}
t->f=true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Node * t=head;
for(char c:word)
{
if(t->next[c]==NULL)
{
return false;
}
t=t->next[c];
}
return t->f;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Node * t=head;
for(char c:prefix)
{
if(t->next[c]==NULL)
{
return false;
}
t=t->next[c];
}
return true;
}
};