题目地址http://hihocoder.com/contest/hiho2/problem/1?sid=146151点击打开链接
输入
输入的第一行为一个正整数n,表示词典的大小,其后n行,每一行一个单词(不保证是英文单词,也有可能是火星文单词哦),单词由不超过10个的小写英文字母组成,可能存在相同的单词,此时应将其视作不同的单词。接下来的一行为一个正整数m,表示小Hi询问的次数,其后m行,每一行一个字符串,该字符串由不超过10个的小写英文字母组成,表示小Hi的一个询问。
在20%的数据中n, m<=10,词典的字母表大小<=2.
在60%的数据中n, m<=1000,词典的字母表大小<=5.
在100%的数据中n, m<=100000,词典的字母表大小<=26.
trie的原理在网上随便都可以找到,在这里就不累赘了,直接贴AC的代码
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.InputStream;
import static java.lang.System.in;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public class Main {
//static InputStream ins = System.in;
public static void main(String[] args) throws Exception {
// File file = new File("src/in");
// System.out.println(file.getAbsolutePath());
// InputStream ins = new FileInputStream(file);
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
Trie trie = new Trie();
String str = "";
while (n-- != 0) {
str = cin.next();
trie.insert(str);
}
n = cin.nextInt();
while (n-- != 0) {
str = cin.next();
System.out.println(trie.getCount(str));
}
}
public static class Trie {
private TrieNode head;
public Trie() {
this.head = new TrieNode(null);
// this.head.set('\0');
}
public void insert(String vocabulary) {
char chs[] = vocabulary.toCharArray();
TrieNode pre = head;
for (int i = 0; i < chs.length; ++i) {
TrieNode trieNode = pre.set(chs[i]);
trieNode.CountAdd();
pre = trieNode;
}
}
public int getCount(String vocabulary) {
char[] chs = vocabulary.toCharArray();
TrieNode pre = head;
TrieNode trieNode = null;
for (char t : chs) {
trieNode = pre.get(t);
if (trieNode == null) {
return 0;
}
pre = trieNode;
}
return trieNode.getCount();
}
public static class TrieNode {
HashMap<Character, TrieNode> map;
private int count = 0;
private Character value = 0;
public static int SIZE = 256;
public TrieNode(Character ch) {
this.value = ch;
map = new HashMap<>(SIZE);
}
public TrieNode(Character ch, boolean flag) {
this(ch);
this.count = 1;
}
public TrieNode get(Character ch) {
return map.get(ch);
}
public TrieNode set(Character ch) {
TrieNode t = map.get(ch);
if (t == null) {
t = new TrieNode(ch);
this.map.put(ch, t);
}
return t;
}
public int getCount() {
return this.count;
}
public Character getValue() {
return this.value;
}
public void CountAdd() {
this.count++;
}
}
}
}