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

Trie 树

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

插入字符串

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

从字符a开始寻找:

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

找寻字符b:

查看spb是否存在,若不存在,创建spb= ++idx,若不存在,不做操作,p = spa

同样方法找寻字符'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,返回cntp即为字符串的个数

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;
        }
    }
    
}
相关推荐
Ada's8 小时前
【计算机基础系列】003:Python数据结构
开发语言·数据结构·python
Nil2089 小时前
leetcode 118杨辉三角
算法·leetcode·职场和发展
NeilYuen10 小时前
【C++】STL源码仿写(二):vector
开发语言·c++
郝学胜_神的一滴11 小时前
游戏引擎原理与实践 04:拆解引擎基础系统与内存管理
c++·游戏
wanderist.11 小时前
线性筛法详解:从筛质数到欧拉函数、Möbius 函数与约数函数
java·数据结构·算法
All for pursuit.11 小时前
【设计-1】208.实现Trie (前缀树)
数据结构·c++·算法·leetcode
weixin_3077791311 小时前
C++代码实现MATLAB中的crossval函数功能
开发语言·c++·算法·matlab
青少儿编程课堂12 小时前
背包问题(0/1 背包与完全背包)解题精讲——动态规划入门
c++·python·算法·bfs·信息学竞赛
倒头就睡的小比特12 小时前
C++多态
c++
光影少年12 小时前
为什么 JavaScript 中 0.1 + 0.2 !== 0.3,如何让其相等?
前端·javascript·算法