缝缝补补 就过了 仅供参考
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] split = br.readLine().split(" ");
int n = Integer.parseInt(split[0]);
int m = Integer.parseInt(split[1]);
Trie t = new Trie();
String[] word = new String[n];
String[] inquire = new String[m];
for (int i = 0; i < n; i++) {
word[i] = br.readLine();
t.insert(word[i]);
}
for (int i = 0; i < m; i++) {
inquire[i] = br.readLine();
t.startsWith(inquire[i]);
// System.out.println(res);
}
}
static class Trie {
Node root;
class Node {
Node[] child;
int cnt;
public Node() {
child = new Node[26];
cnt = 0;
}
}
public Trie() {
root = new Node();
}
public void insert(String word) {
Node cur = root;
for (char c : word.toCharArray()) {
if (cur.child[c - 'a'] == null) {
cur.child[c - 'a'] = new Node();
}
cur = cur.child[c - 'a'];
}
cur.cnt++;
}
public void startsWith(String prefix) {
Node cur = root;
int res = 0;
for (int i = 0; i < prefix.length(); i++) {
if (cur == null) {
break;
}
res += cur.cnt;
cur = cur.child[prefix.charAt(i) - 'a'];
}
if (cur != null) {
res += cur.cnt;
}
System.out.println(res);
}
}
}