您的位置:首页 > 其它

hihoCoder 1014 Trie树 题解

2018-01-21 09:35 387 查看
题目大意:

  这个题目主要是给定n个字符串构建字典,然后再给出m个字符串,从中找出m个字符串在n个字符串中有多少个是其前缀。

分析:

  通过对n个字符串构建字典树,然后再读入m个字符串在字典树上进行查找,那么每一次对字典树的插入或者查找的时间复杂度为O(length(String)),因此总的时间复杂度为:

max(n, m) * O(length(String))。

源代码:

import java.util.*;
import java.io.*;

public class Main {
static int n, m;
static String str = null;
static class Node {
int num;
Node next[];
public Node() {
num = 1;
next = new Node[26];
for(int i = 0; i < 26; i++) {
next[i] = null;
}
}
}
static Node root = new Node();
public static void insert() {
Node p = root, q = null;
int index;
for(int i = 0; i < str.length(); i++) {
index = str.charAt(i) - 'a';
if(p.next[index] == null) {
q = new Node();
p.next[index] = q;
p = p.next[index];
} else {
p = p.next[index];
p.num++;
}
}
}
public static int find() {
Node p = root;
int index;
for(int i = 0; i < str.length(); i++) {
index = str.charAt(i) - 'a';
if(p.next[index] == null) {
return 0;
}
p = p.next[index];
}
return p.num;
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
n = in.nextInt();
for(int i = 0; i < n; i++) {
str = in.next();
insert();
}
m = in.nextInt();
for(int i = 0; i < m; i++) {
str = in.next();
out.println(find());
}
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while(tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: