AcWing 142. [java]前缀统计
原题链接
简单
作者:
acao8864
,
2020-07-31 04:36:15
,
所有人可见
,
阅读 596
代码
import java.util.Scanner;
class Node {
int cnt;
Node[] son;
public Node() {
cnt = 0;
son = new Node[26];
}
}
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), m = in.nextInt();
Node trie = new Node();
for (int i = 0; i < n; ++i) {
String s = in.next();
insert(s, trie);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < m; ++i) {
String s = in.next();
query(s, trie, sb);
}
in.close();
System.out.print(sb);
}
private static void insert(String s, Node trie) {
int n = s.length();
for (int i = 0; i < n; ++i) {
int id = s.charAt(i) - 'a';
if (trie.son[id] == null) {
trie.son[id] = new Node();
}
trie = trie.son[id];
}
trie.cnt++;
}
private static void query(String s, Node trie, StringBuilder sb) {
int ans = 0;
for (int i = 0; i < s.length(); ++i) {
int id = s.charAt(i) - 'a';
if (trie == null) break;
ans += trie.cnt;
trie = trie.son[id];
}
if (trie != null) ans += trie.cnt;
sb.append(ans);
sb.append("\n");
}
}