字典树(Trie)
2016-11-27 15:03
204 查看
字典树
字典树,又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
应用
(1)自动匹配
(2)拼写检查
(3)IP路由(寻找最长匹配)
(4)T9文本输入
(5)解决单词游戏
实现方法
(1) 从根结点开始一次搜索;
(2) 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索;
(3) 在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索。
(4) 迭代过程……
(5) 在某个结点处,关键词的所有字母已被取出,则读取附在该结点上的信息,即完成查找。
其他操作类似处理
具体实现(C++)
时间复杂度O(m),m是单词的长度
参考leetcode–Implement Trie和百度百科
字典树,又称单词查找树,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和百度百科
相关文章推荐
- 字典树trie_tree
- 【算法】Trie数(前缀树/字典树)简介及Leetcode上关于前缀树的题
- (字典树Trie Tree)HDU 1251 统计难题
- 字典树(trie)
- Data Structure: Trie(字典树)
- HDU-1305 Immediate Decodability (Trie 字典树 入门题)
- POJ 2503 Babelfish(字典树Trie)
- zoj 3228 trie tree(字典树)
- HDU 1671 Phone List(字典树Trie)
- LeetCode211. Add and Search Word - Data structure design前缀树(Trie,字典树)实战
- HDU5687(字典树Trie增删查)
- 详解字典树Trie结构及其Python代码实现
- Trie(字典树)学习小结1
- 用KMP算法与Trie字典树实现屏蔽敏感词(UTF-8编码)
- POJ2001 - 字典树(trie)的模板题
- 【HDU - 5845】Best Division(xor-trie、01字典树、dp)
- Trie(前缀树,字典树)
- Data Structure: Trie(字典树)
- Trie 树(又称字典树,单词查找树)
- trie 字典树 POJ 2513