Trie
前缀树,高效的存储和查找字符串集合的数据结构
这里是最基本的前缀树模版,关于前缀树,之前写过一篇用前缀树写敏感词过滤器的文章,
模版题:
维护一个字符串集合,支持两种操作:
I x
向集合中插入一个字符串 xx;Q x
询问一个字符串在集合中出现了多少次。
共有 NN 个操作,输入的字符串总长度不超过 105105,字符串仅包含小写英文字母。
输入格式
第一行包含整数 NN,表示操作数。
接下来 NN 行,每行包含一个操作指令,指令为 I x
或 Q x
中的一种。
输出格式
对于每个询问指令 Q x
,都要输出一个整数作为结果,表示 xx 在集合中出现的次数。
每个结果占一行。
数据范围
1≤N≤2∗1041≤N≤2∗104
输入样例:
5
I abc
Q abc
Q ab
I ab
Q ab
输出样例:
1
0
1
import java.util.*;
public class Main {
static final int N = 100010;
static int[][] son = new int[N][26];
static int[] cnt = new int[N];
static int idx;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while(n-- > 0) {
String ops = sc.next();
if(ops.equals("I")) {
String s = sc.next();
insert(s);
} else {
String s = sc.next();
System.out.println(query(s));
}
}
}
// 插入字符串
public static void insert(String s) {
int p = 0;
for(int i = 0; i < s.length(); ++i) {
int u = s.charAt(i) - 'a';
if(son[p][u] == 0) {
son[p][u] = ++idx;
}
p = son[p][u];
}
cnt[p]++;
}
// 查询字符串在集合中出现的次数
public static int query(String s) {
int p = 0;
for(int i = 0; i < s.length(); ++i) {
int u = s.charAt(i) - 'a';
if(son[p][u] == 0) {
return 0;
}
p = son[p][u];
}
return cnt[p];
}
}
评论区