原题链接
①. 题目
②. 思路
- 使用Trie树:高效地存储和查找字符串集合的数据结构,
- 对与向集合插入一个字符串,从头开始变量字符串,使用字符匹配Trie树中的每一个节点,若存在,直接跳到下一个相应的节点,若不存,则创建新的节点。
- 对于查询有多少个字符串,一样的搜索Trie树,若某个节点不存在,则没有,若存在,一直跳到最后一个节点,再访问这个被标记的节点上有多少个字符串
③. 学习点
Trie 树
④. 代码实现
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class _836_Trie字符串统计_二维数组模拟Trie树 {
static int N=100010,idx=0;
static int[][] trie=new int[N][26];
static int[] cnt=new int[N];
public static void insert(char[] c) {
int p=0;
for (int i = 0; i < c.length; i++) {
int t=c[i]-'a';
if(trie[p][t]==0) {
trie[p][t]=++idx;
}
p=trie[p][t];
}
cnt[p]++;
}
public static int query(char[] c) {
int p=0;
for (int i = 0; i < c.length; i++) {
int t=c[i]-'a';
if(trie[p][t]==0) {
return 0;
}
p=trie[p][t];
}
return cnt[p];
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
while(n-->0) {
String[] s = br.readLine().split(" ");
if(s[0].equals("I")) {
insert(s[1].toCharArray());
}else if(s[0].equals("Q")){
System.out.println(query(s[1].toCharArray()));
}
}
}
}
使用HashMap模拟Trie树
import java.io.*;
import java.util.*;
public class _836_Trie字符串统计_HashMap模板 {
static class Node{
char val;
int count;
Map<Character,Node> children;
Node(){};
Node(char val){
this.val=val;
}
}
static Node root;
public static void insert(String s) {
Node node=root;
for(int i=0;i<s.length();i++) {
char c = s.charAt(i);
if(node.children==null) {
node.children=new HashMap();
}
if(!node.children.containsKey(c)) {
node.children.put(c, new Node(c));
}
node=node.children.get(c);
}
node.count++;
}
public static int search(String s) {
Node node=root;
for(int i=0;i<s.length();i++) {
char c = s.charAt(i);
if(node.children==null || !node.children.containsKey(c)) {
return 0;
}
node=node.children.get(c);
}
return node.count;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
root=new Node();
while(n-->0) {
String[] s = br.readLine().split(" ");
if(s[0].equals("I")) {
insert(s[1]);
}else {
System.out.println(search(s[1]));
}
}
}
}