【数据结构】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;
        }
    }
    
}
相关推荐
moonsea0203几秒前
【无标题】
算法
佑白雪乐21 分钟前
<ACM进度212题>[2026-3-1,2026-3-26]
算法·leetcode
穿条秋裤到处跑24 分钟前
每日一道leetcode(2026.03.26):等和矩阵分割 II
算法·leetcode·矩阵
平凡灵感码头29 分钟前
C语言 printf 数据打印格式速查表
c语言·开发语言·算法
哔哔龙34 分钟前
Android OpenCV 实战:图片轮廓提取与重叠轮廓合并处理
android·算法
hz_zhangrl37 分钟前
CCF-GESP 等级考试 2026年3月认证C++三级真题解析
c++·算法·程序设计·gesp·gesp2026年3月·gesp c++三级
x_xbx41 分钟前
LeetCode:1. 两数之和
数据结构·算法·leetcode
x_xbx43 分钟前
LeetCode:49. 字母异位词分组
算法·leetcode·职场和发展
玲娜贝儿--努力学习买大鸡腿版1 小时前
hot 100 刷题记录(1)
数据结构·python·算法
123过去1 小时前
pixiewps使用教程
linux·网络·测试工具·算法·哈希算法