【数据结构】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;
        }
    }
    
}
相关推荐
NAGNIP3 小时前
万字长文!回归模型最全讲解!
算法·面试
知乎的哥廷根数学学派3 小时前
面向可信机械故障诊断的自适应置信度惩罚深度校准算法(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习·矩阵
txinyu的博客3 小时前
解析业务层的key冲突问题
开发语言·c++·分布式
666HZ6664 小时前
数据结构2.0 线性表
c语言·数据结构·算法
SmartRadio4 小时前
ESP32添加修改蓝牙名称和获取蓝牙连接状态的AT命令-完整UART BLE服务功能后的完整`main.c`代码
c语言·开发语言·c++·esp32·ble
余瑜鱼鱼鱼5 小时前
Java数据结构:从入门到精通(十二)
数据结构
实心儿儿5 小时前
Linux —— 基础开发工具5
linux·运维·算法
charlie1145141916 小时前
嵌入式的现代C++教程——constexpr与设计技巧
开发语言·c++·笔记·单片机·学习·算法·嵌入式
清木铎7 小时前
leetcode_day4_筑基期_《绝境求生》
算法
清木铎7 小时前
leetcode_day10_筑基期_《绝境求生》
算法