【数据结构】21 Trie字符串统计

Trie 树

Trie树又称字典树、单词查找树。是一种能够高效存储和查找字符串集合的数据结构。

插入字符串

对上面已知的tire树,假如插入一个字符串"abdf",需要进行以下操作:

从字符a开始寻找:

从第一层开始p =0 ,s[p][a]是否存在,若不存在,则创建s[p][a]=++idx; 若存在,不做操作,记p = s[p][a];

找寻字符b:

查看s[p][b]是否存在,若不存在,创建s[p][b]= ++idx,若不存在,不做操作,p = s[p][a]

同样方法找寻字符'd','f'

查找完成后,把该字符串出现次数加一

cpp 复制代码
void Insert(string str){
    int p =0;
    for(int i=0; str[i]!='\0';i++){
        int u = str[i] - 'a';
        if(!s[p][u]){
            s[p][u] = ++idx;
        }
        p = s[p][u];
    }
    cnt[p] ++;
}

查找字符串出现次数

从第一个字符开始,如果没找到,直接返回0;一直找到最后一个字符,返回最后一个字符的下一个位置p,返回cnt[p]即为字符串的个数

cpp 复制代码
int find(string str){
    int p = 0;
    for(int i =0 ; str[i]!='\0';i++){
        int u = str[i]-'a';
        if(!s[p][u]){
            return 0;
        }
        else{
            p = s[p][u];
        }
    }
    return cnt[p];
}

完整代码

对应acwing 835题

cpp 复制代码
# include <iostream>
# include <cstring>

using namespace std;

const int n = 100010;
int s[n][26];
int cnt[n];
int idx;
string str;

void Insert(string str){
    int p =0;
    for(int i=0; str[i]!='\0';i++){
        int u = str[i] - 'a';
        if(!s[p][u]){
            s[p][u] = ++idx;
        }
        p = s[p][u];
    }
    cnt[p] ++;
}

int find(string str){
    int p = 0;
    for(int i =0 ; str[i]!='\0';i++){
        int u = str[i]-'a';
        if(!s[p][u]){
            return 0;
        }
        else{
            p = s[p][u];
        }
    }
    return cnt[p];
}

int main(){
    int m;
    int i=0;
    cin>>m;
    while(m--){
        char op;
        cin>>op>>str;
        if(op == 'I'){Insert(str);}
        else{
            cout<<find(str)<<endl;
        }
    }
    
}
相关推荐
码农多耕地呗39 分钟前
力扣146.LRU缓存(哈希表缓存.映射+双向链表数据结构手搓.维护使用状况顺序)(java)
数据结构·leetcode·缓存
程序员老舅1 小时前
C++参数传递:值、指针与引用的原理与实战
c++·c/c++·值传递·引用传递·指针传递·参数传递机制
晚枫~1 小时前
数据结构基石:从线性表到树形世界的探索
数据结构
hadage2332 小时前
--- 数据结构 AVL树 ---
数据结构·算法
liu****2 小时前
8.list的使用
数据结构·c++·算法·list
立志成为大牛的小牛2 小时前
数据结构——二十六、邻接表(王道408)
开发语言·数据结构·c++·学习·程序人生
阿拉丁的梦2 小时前
后期材质-屏幕冲击径向模糊
算法·材质
weixin_429630262 小时前
实验二-决策树-葡萄酒
算法·决策树·机器学习
草莓熊Lotso3 小时前
C++ 方向 Web 自动化测试入门指南:从概念到 Selenium 实战
前端·c++·python·selenium
茉莉玫瑰花茶3 小时前
floodfill 算法(dfs)
算法·深度优先