当前位置:网站首页>字符串——Trie
字符串——Trie
2022-08-01 21:59:00 【ThXe】
Trie
维护一个字符串集合,支持两种操作:
I x 向集合中插入一个字符串 x;
Q x 询问一个字符串在集合中出现了多少次。
假设所有字符串长度之和为n,构建字典树的时间复杂度为O(n)
假设要查找的字符串长度为k,查找的时间复杂度为O(k)
拓展应用:
1.一个字符串是集合中多少个字符串的前缀
解法:每个节点都计数即可
//Trie树快速存储字符集合和快速查询字符集合
//支持大小写+数字
#include<bits/stdc++.h>
using namespace std;
const int N = 3000001;
//son[][]存储子节点的位置,分支最多26条;
//cnt[]存储以某节点结尾的字符串个数(同时也起标记作用)
//idx表示当前要插入的节点是第几个,每创建一个节点值+1
int son[N][65], cnt[N], idx;
char str[N];
int getnum(char x) {
if (x >= 'A' && x <= 'Z')
return x - 'A';
else if (x >= 'a' && x <= 'z')
return x - 'a' + 26;
else
return x - '0' + 52;
}
void insert(char* str)
{
int p = 0; //类似指针,指向当前节点
for (int i = 0; str[i]; i++)
{
int u =getnum(str[i]); //将字母转化为数字
if (!son[p][u]) son[p][u] = ++idx; //该节点不存在,创建节点
p = son[p][u]; //使“p指针”指向下一个节点
cnt[p]++; //结束时的标记,也是记录以此节点结束的字符串个数(前缀)
}// cnt[p]++出现次数
}
int query(char* str)
{
int p = 0;
for (int i = 0; str[i]; i++)
{
int u = getnum(str[i]);
if (!son[p][u]) return 0; //该节点不存在,即该字符串不存在
p = son[p][u];
}
return cnt[p]; //返回字符串出现的次数
}
int main()
{
int t; cin >> t;
while (t--)
{
int n, m;
cin >> n >> m;
for (int i = 0; i <= idx; i++)
for (int j = 0; j <= 64; j++)
son[i][j] = 0;
for (int i = 0; i <= idx; i++)
cnt[i] = 0;
idx = 0;
for (int i = 1; i <= n; i++)
{
cin >> str;
insert(str);
}
for (int i = 1; i <= m; i++)
{
cin >> str;
cout << query(str)<<endl;
}
}
return 0;
}
边栏推荐
猜你喜欢
模拟数据之mockjs
小程序中的多表联合查询
AI应用第一课:支付宝刷脸登录
Analysis of the development trend of game metaverse
第一讲 测试知多少
The difference between groupByKey and reduceBykey
基于php影视资讯网站管理系统获取(php毕业设计)
Advanced Algebra_Proof_The algebraic multiplicity of any eigenvalue of a matrix is greater than or equal to its geometric multiplicity
The must-have "fishing artifact" for programmers is here!
[Niu Ke brush questions-SQL big factory interview questions] NO4. Travel scene (a taxi)
随机推荐
MySQL相关知识
The Microsoft campus ambassador to shout you to autumn recruit!
more grown, more lonely
漫长的投资生涯
高等代数_证明_矩阵的任意特征值的代数重数大于等于其几何重数
SOM Network 2: Implementation of the Code
Based on php film and television information website management system acquisition (php graduation design)
基于 OData 模型和 JSON 模型的 SAP UI5 表格控件行项目的添加和删除实现
熟悉的朋友
还在纠结报表工具的选型么?来看看这个
基于php影视资讯网站管理系统获取(php毕业设计)
求解多元多次方程解的个数
Spark shuffle调优
Kubernetes第零篇:认识kubernetes
2022-08-01 第八组 曹雨 泛型 枚举
Pagoda application experience
Based on php hotel online reservation management system acquisition (php graduation project)
LeetCode952三部曲之一:解题思路和初级解法(137ms,超39%)
不卷了!入职字节跳动一周就果断跑了。
高等代数_证明_矩阵的行列式为特征值之积, 矩阵的迹为特征值之和