参考链接:
Java实现:
import java.io.BufferedInputStream;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
//构建字典树
int n = sc.nextInt();
Trie root = new Trie();//构建一棵空树,不断的往里面放节点。
for(int i = 0;i<n;i++){
insert(root, sc.next());
}
//查找字典树
int m = sc.nextInt();
for(int i = 0;i<m;i++){
System.out.println(find(root, sc.next()));
}
}
//创建字典树
public static void insert(final Trie root, String str) {
Trie cur = root;
for (char ch : str.toCharArray()) {
int idx = ch - 'a';
if (cur.child[idx] == null) {
cur.child[idx] = new Trie();
}
cur = cur.child[idx];
cur.num++;
}
}
//查找字典树
public static int find(final Trie root, String str) {
Trie cur = root;
for (char ch : str.toCharArray()) {
int idx = ch - 'a';
if (cur.child[idx] == null) {
return 0;
}
cur = cur.child[idx];
}
return cur.num;
}
}
class Trie {
Trie[] child;
int num;
public Trie() {
child = new Trie[26];
}
}