字典树也叫Trie,是一种树形结构,其中每个节点可以存储一些变量表示该字符串出现的数量。每条边表示一个字符,如节点9存储一个变量cnt,说明存在三个字符串为“cbc”
例题:前缀判定
import java.math.BigInteger; import java.util.*;public class Main {static class TreeNode{HashMap<Character,TreeNode>map;int cnt;public TreeNode(){cnt=0;map=new HashMap<>();}}static TreeNode root;//根节点//插入字符串public static void insert(String s){TreeNode c=root;for(int i=0;i<s.length();i++){char x=s.charAt(i);if(!c.map.containsKey(x)){c.map.put(x,new TreeNode());c.cnt++;}c=c.map.get(x);}c.cnt++;}//查询字符串是否出现public static boolean query(String s){TreeNode c=root;for(int i=0;i<s.length();i++){if(!c.map.containsKey(s.charAt(i))){return false;}c=c.map.get(s.charAt(i));}return c.cnt>0;}//查找出现的次数public static int query1(String s){TreeNode c=root;for(int i=0;i<s.length();i++){if(!c.map.containsKey(s.charAt(i))){return 0;}c=c.map.get(s.charAt(i));}return c.cnt;}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int n=scanner.nextInt();int m=scanner.nextInt();root=new TreeNode();for(int i=0;i<n;i++){String s=scanner.next();insert(s);}for(int i=0;i<m;i++){String s=scanner.next();if(query(s)){System.out.println("Y");}else{System.out.println("N");}}//出现的前缀System.out.println(query1("aa"));}}