Java 代码
使用树来表示,理解起来更简单
import java.io.BufferedInputStream;
import java.util.*;
public class Main{
public static void main(String [] args){
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int n = sc.nextInt();
sc.nextLine();
Trie trie = new Trie();
for(int i=0;i<n;i++){
String str = sc.nextLine();
//System.out.println(str);
String [] strs = str.split(" ");
if("I".equals(strs[0])){
trie.insert(strs[1]);
}else{
int res = trie.query(strs[1]);
System.out.println(res);
}
}
}
}
class Trie{
private TreeNode root = new TreeNode();
public void insert(String str){
char [] chars = str.toCharArray();
TreeNode p = root;
for(int i=0;i<chars.length;i++){
int index = chars[i] - 'a';
if(p.children[index]==null){
TreeNode node = new TreeNode();
p.children[index] = node;
}
p = p.children[index];
}
p.endCount++;
}
public int query(String str) {
char [] chars = str.toCharArray();
TreeNode p = root;
for(int i=0;i<chars.length;i++){
int index = chars[i] - 'a';
if(p.children[index]==null){
return 0;
}
p = p.children[index];
}
return p.endCount;
}
}
class TreeNode{
int endCount = 0;
TreeNode[] children = new TreeNode[26];
}