AcWing 835. Trie字符串统计--Java--数组模拟
原题链接
简单
import java.util.Scanner;
public class Acwing835 {
int N = 100000 + 10;
int idx = 0;
int[][] son = new int[N][26];
int[] cnt = new int[N];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Acwing835 ins = new Acwing835();
ins.solve(sc);
sc.close();
}
private void solve(Scanner sc) {
int n = sc.nextInt();
String line = sc.nextLine();
for (int i = 0; i < n; i++) {
String[] s = sc.nextLine().split(" ");
String op = s[0];
String str = s[1];
if ("I".equals(op)) {
insert(str);
} else {
if ("Q".equals(op)) {
System.out.println(query(str));
}
}
}
}
private void insert(String s) {
char[] chs = s.toCharArray();
int n = chs.length;
int par = 0;
for (int i = 0; i < n; i++) {
int t = chs[i] - 'a';
if (son[par][t] == 0) son[par][t] = ++idx;
par = son[par][t];
}
cnt[par]++;
}
private int query(String s) {
char[] chs = s.toCharArray();
int n = chs.length;
int par = 0;
for (int i = 0; i < n; i++) {
int t = chs[i] - 'a';
if (son[par][t] == 0) return 0;
par = son[par][t];
}
return cnt[par];
}
}