Trie的实现

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");



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值