您的位置:首页 > 其它

字典树(Trie)

2016-11-27 15:03 204 查看
字典树

字典树,又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。

应用

(1)自动匹配

(2)拼写检查

(3)IP路由(寻找最长匹配)

(4)T9文本输入

(5)解决单词游戏

实现方法

(1) 从根结点开始一次搜索;

(2) 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索;

(3) 在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索。

(4) 迭代过程……

(5) 在某个结点处,关键词的所有字母已被取出,则读取附在该结点上的信息,即完成查找。

其他操作类似处理

具体实现(C++)

class TrieNode {
public:
bool isend;
TrieNode* links[26];
public:
TrieNode(bool b=0)
{
memset(links, 0, sizeof(links));
//links=new TrieNode;
isend=b;
}

~TrieNode(){
for(auto it:links)
delete it;
}
};

class Trie {
public:
Trie() {
root = new TrieNode();
}

// Inserts a word into the trie.
void insert(string word) {
if(search(word)) return;
TrieNode* cur=root;
for(auto ch:word){
if(cur->links[ch-'a']==NULL)
cur->links[ch-'a']=new TrieNode();
cur=cur->links[ch-'a'];
}

cur->isend=true;
}

// Returns if the word is in the trie.
bool search(string word) {
TrieNode* cur=find(word);
return cur!=NULL&&cur->isend;
}

// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
return find(prefix)!=NULL;
}
~Trie()
{
delete root;
}

private:
TrieNode* root;
TrieNode* find(string key){
TrieNode* cur=root;
for(int i=0;i<key.size()&&cur!=NULL;++i)
cur=cur->links[key[i]-'a'];
return cur;
}
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");


时间复杂度O(m),m是单词的长度

参考leetcode–Implement Trie百度百科
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: