AcWing 142. Java-一看就懂
原题链接
简单
作者:
zlnnjit
,
2021-04-14 21:36:24
,
所有人可见
,
阅读 372
import java.util.Scanner;
class Main {
static class TrieNode {
int count = 0;
TrieNode[] tns = new TrieNode[26];
}
static class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
private void insert(String word) {
TrieNode p = root;
for (int i = 0; i < word.length(); i++) {
int u = word.charAt(i) - 'a';
if (p.tns[u] == null) p.tns[u] = new TrieNode();
p = p.tns[u];
}
p.count++;
}
private int countPrefix(String word) {
int ans = 0;
TrieNode p = root;
for (int i = 0; i < word.length(); i++) {
int u = word.charAt(i) - 'a';
if (p.tns[u] == null) break;
ans += p.count;
p = p.tns[u];
}
return ans + p.count;
}
}
public static void main(String args[]) {
Trie trie = new Trie();
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
int n = Integer.parseInt(s[0]), m = Integer.parseInt(s[1]);
for (int i = 0; i < n; i++) trie.insert(sc.nextLine());
for (int i = 0; i < m; i++) System.out.println(trie.countPrefix(sc.nextLine()));
}
}