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