trie - 将唯一元素插入特里
问题描述
void insert(struct node *root, string s)
{
struct node *temp = root;
for(int i=0;i<s.length();i++)
{
if(temp->idx[s[i]-'a']==NULL)
temp->idx[s[i]-'a']=create();
temp = temp->idx[s[i]-'a'];
(temp->cnt)++;
}
temp->end=1;
}
所以我要插入字符串来创建一个唯一的 trie 数据结构,但是这个插入算法无法检测到任何重复的字符串,有人可以帮我这个插入算法如何仅用于插入唯一元素吗?
解决方案
您可以使用end
. struct node
让我们调用 find
这个布尔方法并将其添加为insert
方法的第一行。
bool find(struct node *root, string s)
{
struct node *temp = root;
for(int i=0;i<s.length();i++)
{
if(temp->idx[s[i]-'a']==NULL)
return false;
temp = temp->idx[s[i]-'a'];
}
return temp->end;
}
void insert(struct node *root, string s)
{
if(!find(root, s)) return;
struct node *temp = root;
for(int i=0;i<s.length();i++)
{
if(temp->idx[s[i]-'a']==NULL)
temp->idx[s[i]-'a']=create();
temp = temp->idx[s[i]-'a'];
(temp->cnt)++;
}
temp->end=1;
}
运行时:与之前相同,O(m)
其中.m
s
注意:我制定了find
方法,因为无论如何你最多需要遍历两次 trie 的路径。一种方法是在开头提到的,第二种方法是end
在您拥有代表的节点时检查重复项(属性)s
,如果它确实是一个重复的字符串,那么您再次遍历s
路径来修复属性中额外的 +1 cnt
。
推荐阅读
- javascript - React - Redux-Form Remote Submit
- android - 如何在颤动中动态改变步进器的步数?
- java - Java JDBC 程序在从表中获取特定行时抛出 SQL 语法错误
- javascript - 即使有断言,Jest 也会将测试标记为成功
- java - ItemClickListener 在带有 onclick 的 Fragment RecyclerView 中不起作用
- python - 如何在python中以编程方式比较动态变量
- python - 对包含列表作为值的字典列表进行排序
- json - 使用插值显示 HTML 信息
- html - 如何将标签链接到 html 文本而不是文件?
- c# - 使用 SimpleInjector 的二进制 PowerShell Core cmdlet 导致 FileNotFoundException