前缀树(Trie树)

Trie树

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

    Trie的核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。
它有3个基本性质:

  1. 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
  2. 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
  3. 每个节点的所有子节点包含的字符都不相同。

前缀查询

    上文中提到”比如说对于某一个单词,我们要询问它的前缀是否出现过。这样hash就不好搞了,而用trie还是很简单“。下面,咱们来看看这个前缀查询问题:

    已知n个由小写字母构成的平均长度为10的单词,判断其中是否存在某个串为另一个串的前缀子串。下面对比3种方法:

  1. 最容易想到的:即从字符串集中从头往后搜,看每个字符串是否为字符串集中某个字符串的前缀,复杂度为O(n^2)。
  2. 使用hash:我们用hash存下所有字符串的所有的前缀子串,建立存有子串hash的复杂度为O(n*len),而查询的复杂度为O(n)* O(1)= O(n)。
  3. 使用trie:因为当查询如字符串abc是否为某个字符串的前缀时,显然以b,c,d....等不是以a开头的字符串就不用查找了。所以建立trie的复杂度为O(n*len),而建立+查询在trie中是可以同时执行的,建立的过程也就可以成为查询的过程,hash就不能实现这个功能。所以总的复杂度为O(n*len),实际查询的复杂度也只是O(len)。(说白了,就是Trie树的平均高度h为len,所以Trie树的查询复杂度为O(h)=O(len)。好比一棵二叉平衡树的高度为logN,则其查询,插入的平均时间复杂度亦为O(logN))。
#include <iostream>
#include <cstring>
#include <string>
using namespace std;

const int branchNum = 26;
struct TrieNode{
    bool isStr;
    TrieNode* next[branchNum];
    TrieNode(){
        isStr = false;
        memset(next,NULL,sizeof(next));
    }
};

void InsertTrie(TrieNode* root, string& str){
    TrieNode* location = root;
    int len = str.size(),i=0;

    while(i<len){
        if(!location->next[str[i]-'a']){
            TrieNode* newNode = new TrieNode();
            location->next[str[i]-'a'] = newNode;
        }
        location = location->next[str[i]-'a'];
        i+=1;
    }
    location->isStr = true;
}

bool SerachTrie(TrieNode* root, string& str){
    int len = str.size(),i=0;
    TrieNode *location = root;
    while(i<len&&location){
        location = location->next[str[i]-'a'];
        i+=1;
    }
    return location&&location->isStr;
}

void Delete(TrieNode* root){
    TrieNode* location = root;
    for(int i=0;i<branchNum;i++){
        if(location->next[i]) Delete(location->next[i]);
    }
    delete location;
    location = NULL;
}

int main(){
    TrieNode* root = new TrieNode();

    string s1 = "abcd";
    string s2 = "adg";
    InsertTrie(root, s1);
    InsertTrie(root, s2);

    if(SerachTrie(root,s2)){
        std::cout<<"adg exists!"<<std::endl;
    }

    string s3 = "bashk";
    if(SerachTrie(root,s3)){
        std::cout<<"bashk exists!"<<std::endl;       
    }

    Delete(root);
}

参考:trie树(前缀树) - 罗松超 - 博客园 (cnblogs.com)

LeetCode

struct TrieNode{
    string word;
    TrieNode* next[26];
    TrieNode(){
        word = "";
        memset(next,0,sizeof(next));
    }
};

class Solution {
public:
    TrieNode* root;

    void buildTrie(vector<string>& dicts){
        root = new TrieNode();
        for(auto &dict:dicts){
            TrieNode* cur = root;
            for(auto &ch : dict){
                if(!cur->next[ch-'a'])
                    cur->next[ch-'a'] = new TrieNode();

                cur = cur->next[ch-'a'];
            }
            cur->word = dict;
        }
    }

    string replaceWords(vector<string>& dictionary, string sentence) {
        buildTrie(dictionary);
        stringstream  iss(sentence);
        string temp;
        string res;
        while(getline(iss,temp,' ')){
            TrieNode* cur = root;
            for(auto &ch : temp){
                if(!cur->next[ch-'a']) 
                    break;
                else {
                    cur = cur->next[ch-'a'];
                    if(!cur->word.empty()) break;
                }
            }

            res += cur->word.empty() ? temp : cur->word;
            res += " ";
        }
        res.pop_back();
        return res;
    }
};
  • 前缀树的叶子节点可以存放字符串。除了存放结束标记。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值