Trie—单词查找树
Trie,又称单词查找树、前缀树,是一种哈希树的变种。应用于字符串的统计与排序,经常被搜索引擎系统用于文本词频统计。
性质:
1.根节点不包含字符,除根节点外的每一个节点都只包含一个字符。
2.从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
3.每个节点的所有子节点包含的字符都不相同。
优点:
1.查询快:对于长度为m的键值,最坏情况下只需花费O(m)的时间;而BST需要O(m log n)的时间。
2.当存储大量字符串时,Trie耗费的空间较少。因为键值并非显式存储的,而是与其他键值共享子串。
操作:
1.初始化或清空:遍历Trie,删除所有节点,只保留根节点。
2.插入字符串
1).设置当前节点为根节点,设置当前字符为插入字符串中的首个字符;
2).在当前节点的子节点上搜索当前字符,若存在,则将当前节点设为值为当前字符的子节点;否则新建一个值为当前字符的子节点,并将当前结点设置为新创建的节点。
3).将当前字符设置为串中的下个字符,若当前字符为0,则结束;否则转2.
3.查找字符串
搜索过程与插入操作类似,当字符找不到匹配时返回假;若全部字符都存在匹配,判断最终停留的节点是否为树叶,若是,则返回真,否则返回假。
4.删除字符串
首先查找该字符串,边查询边将经过的节点压栈,若找不到,则返回假;否则依次判断栈顶节点是否为树叶,若是则删除该节点,否则返回真。
#include <bits/stdc++.h>
using namespace std;
typedef struct TrieNode
{
int cnt;//已有的单词数
TrieNode *next[26];//下一节点
}TrieNode, *Trie;
//新建一个节点
TrieNode* createTrieNode()
{
TrieNode* root = (Trie)malloc(sizeof(TrieNode));//指向根节点的指针
root->cnt = 0;
memset(root->next, 0, sizeof(root->next));
return root;
}
//插入单词
void insertWord(Trie root, char *word)
{
Trie node = root;
char *p = word;
while(*p)
{
if(node->next[*p-'a'] == NULL)
{
node->next[*p-'a'] = createTrieNode();
}
node = node->next[*p-'a'];
p++;
}
node->cnt += 1;
}
//删除单词
void deleteWord(Trie root, char *word)
{
Trie node = root;
char *p = word;
if(!node)
return;
}
//查找单词是否存在
bool searchWord(Trie root, char *word)
{
Trie node = root;
char *p = word;
while(*p && node!=NULL)
{
node = node->next[*p-'a'];
p++;
}
return (node!=NULL && !node->cnt);
}
//查询单词出现的次数
int cntWord(Trie root, char *word)
{
Trie node = root;
char *p = word;
while(*p)
{
node = node->next[*p-'a'];
p++;
}
return node->cnt;
}
int main()
{
Trie t = createTrieNode();//指向树根节点的指针
char word[][10] = {"test","study","open","show","shit","work","work","test","tea","word","area","word","test","test","test"};
for(int i = 0;i < 15;i++ )
{
insertWord(t,word[i]);
}
for(int i = 0;i < 15;i++ )
{
printf("the word %s appears %d times in the trie-tree\n",word[i],cntWord(t,word[i]));
}
char s[10] = "testit";
printf("the word %s exist? %d \n",s,searchWord(t,s));
return 0;
}