字典树:
又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来节约存储空间,最大限度地减少无谓的字符串比较,查询效率比哈希表高。
字典树的基本功能是用来查询某个单词(前缀)在所有单词中出现次数的一种数据结构,它的插入和查询复杂度都为O(len),Len为单词(前缀)长度,但是它的空间复杂度却非常高,如果字符集是26个字母,那每个节点的度就有26个,典型的以空间换时间结构。
借用网上的图:不知道哪位博主的,先谢谢了。忘记地址了。
代码示例:
#include<iostream>
using namespace std;
int Trie[100][26] = {0};
int bFlag[1000] = { 0 };
int ncount = 1;
void InsertToTrie(char *str)
{
int nLen = strlen(str);
int nroot = 0;
for (int i = 0; i < nLen;i++)
{
int id = str[i] - 'a';
if (Trie[nroot][id] == 0)
{
//不存在,则加入
Trie[nroot][id] = ncount++;
}
//已经存在
nroot = Trie[nroot][id] ;
}
bFlag[ncount] = 1;
}
//查找某个字符串是否存在
bool Triefind(char *str)
{
int nLen = strlen(str);
int nroot = 0;
for (int i = 0; i < nLen; i++)
{
int id = str[i] - 'a';
if (Trie[nroot][id] == 0)
{
return false;
}
//已经存在
nroot = Trie[nroot][id];
}
return bFlag[nroot+1];
}
void main()
{
InsertToTrie("apple");
InsertToTrie("apply");
InsertToTrie("as");
InsertToTrie("at");
InsertToTrie("ok");
InsertToTrie("cash");
InsertToTrie("cat");
bool ret = Triefind("applx");
if (ret)
{
cout << "find applx\n";
}
else
{
cout << "no find applx!\n";
}
ret = Triefind("apple");
if (ret)
{
cout << "find apple\n";
}
else
{
cout << "no find apple!\n";
}
ret = Triefind("cash");
if (ret)
{
cout << "find cash\n";
}
else
{
cout << "no find cash!\n";
}
ret = Triefind("cat");
if (ret)
{
cout << "find cat\n";
}
else
{
cout << "no find cat!\n";
}
ret = Triefind("asx");
if (ret)
{
cout << "find asx\n";
}
else
{
cout << "no find asx!\n";
}
ret = Triefind("ok");
if (ret)
{
cout << "find ok\n";
}
else
{
cout << "no find ok!\n";
}
system("pause");
}
结果:
重要的是理解思想,插入的思想。