Java

Owll 发表于 11个月前 · 关联问题 字典树

题目:字典树

思路:字典树模板题

代码如下:

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class Main { //快速输入 static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //快速输出 static PrintWriter pw=new PrintWriter(new OutputStreamWriter(System.out)); //字符串只有小写英文字母,因此可以用26位的数组记录即可,每一个字符串拥有相同前缀时,cnt+=1 static class Tire{ Tire[] nt; int cnt; public Tire() { nt=new Tire[26]; } } static Tire root; public static void main(String[] args) throws IOException { String s=br.readLine(); int n=Integer.parseInt(s); root=new Tire(); for(int i=0;i<n;i++) { s=br.readLine(); build(s); } s=br.readLine(); int m=Integer.parseInt(s); for(int i=0;i<m;i++) { s=br.readLine(); int ans=count(s); pw.println(ans); } pw.flush(); } private static int count(String s) { Tire rt=root; char[] c=s.toCharArray(); int n=s.length(); for(int i=0;i<n;i++) { int id=c[i]-'a'; if(rt.nt[id]==null) { return 0; } rt=rt.nt[id]; } return rt.cnt; } private static void build(String s) { Tire rt=root; char[] c=s.toCharArray(); int n=s.length(); for(int i=0;i<n;i++) { int id=c[i]-'a'; if(rt.nt[id]==null) { rt.nt[id]=new Tire(); } rt=rt.nt[id]; rt.cnt++; } } }