题目:
插入模拟:假如现在要依次插入cat,car,busy,cate,bus,car
查找:
代码:
import java.util.Scanner;public class Main {public static int[][] ch=new int[100010][26];public static int[] cnt=new int[100010];public static int idx;public static int p;public static void main(String[] args) {Scanner scan=new Scanner(System.in);int n=scan.nextInt();for(int i=0;i<n;i++){String str=scan.next();if(str.charAt(0)=='I'){String s=scan.next();Insert(s);}if(str.charAt(0)=='Q'){String s=scan.next();System.out.println(Query(s));}}}public static void Insert(String s){int p=0;for(int i=0;i<s.length();i++){if(ch[p][s.charAt(i)-'a']==0){ch[p][s.charAt(i)-'a']=++idx;}p=ch[p][s.charAt(i)-'a'];//指针p一直指着当前结点编号。这样当插入下一个结点时,就知道上一个结点编号是啥。}cnt[p]++;//指向单词结尾的指针p代表单词结尾的字符的编号,用cnt记录这个单词的插入次数。}public static int Query(String s){int p=0;for(int i=0;i<s.length();i++){if(ch[p][s.charAt(i)-'a']==0){return 0;}p=ch[p][s.charAt(i)-'a'];}return cnt[p];}
}