题目链接
import java.util.Scanner;
// 字典树的节点
class TrieNode {
boolean isWord;
final TrieNode[] children;
public TrieNode() {
isWord = false;
children = new TrieNode[26];
}
}
// 字典树
class Trie {
TrieNode root;
Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
int c = word.charAt(i) - 'a';
if (current.children[c] == null) {
current.children[c] = new TrieNode();
}
current = current.children[c];
}
current.isWord = true;
}
// 完整的字段树应该包含搜索功能,但是此处用不到
// public boolean search(String word) {
// TrieNode current = root;
// for (int i = 0; i < word.length(); i++) {
// int c = word.charAt(i) - 'a';
// if (current.children[c] == null) {
// return false;
// }
// current = current.children[c];
// }
// return current.isWord;
// }
public boolean startWith(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
int c = word.charAt(i) - 'a';
if (current.children[c] == null) {
return false;
}
current = current.children[c];
}
return true;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
scanner.nextLine(); // 消耗掉换行符
Trie trie = new Trie();
for (int i = 0; i < m; i++) {
trie.insert(scanner.nextLine());
}
for (int i = 0; i < n; i++) {
boolean isStart = trie.startWith(scanner.nextLine());
System.out.println(isStart);
}
}
}