Trie的实现
来源:互联网 发布:深圳数据恢复公司 编辑:程序博客网 时间:2024/06/05 00:59
trie又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
实现方式:
搜索字典项目的方法为:
(1) 从根结点开始一次搜索;
(2) 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索;
(3) 在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索。
(4) 迭代过程……
(5) 在某个结点处,关键词的所有字母已被取出,则读取附在该结点上的信息,即完成查找。
其他操作类似处理
class TrieNode {public: // Initialize your data structure here. TrieNode():child(vector<TrieNode *>(26, NULL)),isWord(false) {} bool isWord; vector<TrieNode *> child;};class Trie {public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(string word) { int size=word.size(); int idx; TrieNode *cur=root;//重点,不要直接使用root,否则就错了 for(int i=0; i<size; i++){ idx=word[i]-'a'; if(cur->child[idx]==NULL) cur->child[idx]=new TrieNode(); cur=cur->child[idx]; } cur->isWord=true; } // Returns if the word is in the trie. bool search(string word) { return hasWord(word.c_str(), root); } bool hasWord(const char * c, TrieNode * cur){ if(cur==NULL) return false; if(*c=='\0')//这里是c,不是c+1,因为第一个字母对应根节点 return cur->isWord; return hasWord(c+1, cur->child[*c-'a']); } bool startPrefix(const char * c, TrieNode*cur){ if(cur==NULL) return false; if(*c=='\0')//这里是跟hasword函数的区别 return true; return startPrefix(c+1, cur->child[*c-'a']);//第一个字母对应根节点,所以不会出错 } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { return startPrefix(prefix.c_str(), root); }private: TrieNode* root;};// Your Trie object will be instantiated and called as such:// Trie trie;// trie.insert("somestring");// trie.search("key");
0 0
- Trie的一个实现
- Trie的java实现
- Trie树的实现
- 简单的trie实现
- Trie树的实现
- Trie的实现
- Trie的实现
- Trie的java实现
- Trie树数据结构的实现
- 一个Trie树的实现
- Trie树的C++实现
- Trie 树的简单实现
- Trie树的C++实现
- 字典树 Trie 的实现
- Trie Tree的c++实现
- Trie树的C++实现
- Trie树的C++实现
- Trie树的C++实现
- (七)面向对象的设计原则之三
- linux系统下快速切换到oracle目录下
- 最小生成树——并查集+Kruskal(NYOJ 38 布线问题)
- 使用构造方法产生对象的原理
- FZU 1003 Counterfeit Dollar
- Trie的实现
- Android 4.0源码下载以及编译
- Online Object Tracking: A Benchmark
- 学习计算机方法二
- 8个值得关注的SQL-on-Hadoop框架
- 多线程断点续传实践
- 仿支付宝/微信的密码输入框效果GridPasswordView解析
- POJ 2528 Mayor's posters 线段树+离散化
- POJ 2492 A Bug's Life(并查集+逻辑关系)