【数据结构】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;
        }
    }
    
}
相关推荐
M78佐菲37 分钟前
c语言学习笔记:排序与查找方法整理
linux·c语言·笔记·学习·算法
别动我齐刘海1 小时前
机器人运动控制学习4——状态估计 State Estimation
c++·人工智能·学习·目标检测·机器学习·机器人·自动驾驶
学习星球1 小时前
OpenHarness 全面配置教学——从游戏开发工作流引入
c++·游戏·ai·ai编程
wWYy.2 小时前
C++与C的区别
c语言·c++
AI备案指南-满满3 小时前
人工智能拟人化互动服务安全自评估报告的评估要点有哪些?
人工智能·算法·安全·机器人·大模型备案·算法备案
LuminousCPP3 小时前
数据结构‑二叉树(二):二叉堆从零实现|Heap结构设计 + 建堆优化 + 堆排序深度解析
c语言·数据结构·笔记·二叉树
土司大王4 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
4 小时前
数据结构第一课:复杂度解析
数据结构
大熊背5 小时前
树莓派IspPipeline LSC模块原理详解
算法·lsc·isppipeline·mesh lsc