码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构——trie树(字典树)

时间:2020-02-06 14:57:24      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:统计   pac   return   ret   保存   name   技术   col   使用   

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

模板题:

技术图片

 

 代码

#include<iostream>
using namespace std;

const int N = 200010;
//用来存放子节点,idx是已经使用的结点下标
int son[N][26],idx;
//用于标记是否有单词
int cnt[N];

void insert(char str[]){
    //p == 0即是根节点,也是空节点
    int p = 0;
    for(int i = 0;str[i];i++){
        int t = str[i] - a;
        //判断是否有当前字符的子节点
        if(!son[p][t]) son[p][t] = ++ idx;
        
        p = son[p][t];
    }
    //标记字符串末尾
    cnt[p]++;
}

int query(char str[]){
    int p = 0;
    for(int i = 0;str[i]; i ++){
        int t = str[i] - a;
        if(!son[p][t]) return 0;
        p = son[p][t];
    }
    if(cnt[p]) return cnt[p];
}

int main(){
    int n;
    cin>>n;
    char ch;
    char str[N];
    for(int i = 0 ; i < n ;i ++){
        cin>>ch>>str;
        if(ch == I){
            insert(str);
        }
        if(ch == Q){
            cout<<query(str)<<endl;
        }
    }
    
    
    
    return 0;
}

 

数据结构——trie树(字典树)

标签:统计   pac   return   ret   保存   name   技术   col   使用   

原文地址:https://www.cnblogs.com/Flydoggie/p/12268269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!