题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
类型:字典树
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Trie trie=new Trie();
Scanner kb = new Scanner(System.in);
boolean pd=true;
int bj=0;
while(kb.hasNextLine()) {
String str=kb.nextLine();
if(str.length()<1) {
pd=false;
continue;
}
if(pd) {
trie.insert(str);
bj++;
}else {
int a=trie.countPrefix(str);
System.out.println(a);
}
}
kb.close();
}
}
class Trie{
private int size=26;
private TrieNode root;
public Trie() {
root=new TrieNode();
}
private class TrieNode{
private int num;
private TrieNode[] son;
private boolean isEnd;
private char val;
public TrieNode() {
num=1;
son=new TrieNode[size];
isEnd=false;
}
}
public void insert(String str) {
if(str==null||str.length()==0)return;
TrieNode node=root;
char letters[]=str.toCharArray();
for(int i=0,len=str.length();i<len;i++) {
int pos=letters[i]-'a';
if(node.son[pos]==null) {
node.son[pos]=new TrieNode();
node.son[pos].val=letters[i];
}else {
node.son[pos].num++;
}
node=node.son[pos];
}
node.isEnd=true;
}
public int countPrefix(String prefix) {
if(prefix==null||prefix.length()==0) {
return -1;
}
TrieNode node=root;
char[]letters=prefix.toCharArray();
for(int i=0,len=prefix.length();i<len;i++) {
int pos=letters[i]-'a';
if(node.son[pos]==null)
return 0;
else
node=node.son[pos];
}
return node.num;
}
public String hasPredix(String prefix) {
if(prefix==null||prefix.length()==0) {
return null;
}
TrieNode node=root;
char[]letters=prefix.toCharArray();
for(int i=0,len=prefix.length();i<len;i++) {
int pos=letters[i]-'a';
if(node.son[pos]==null)
return null;
else
node=node.son[pos];
}
preTraverse(node,prefix);
return prefix;
}
private void preTraverse(TrieNode node, String prefix) {
if (!node.isEnd) {
for (TrieNode child : node.son) {
if (child != null) {
preTraverse(child, prefix + child.val);
}
}
return;
}
System.out.println(prefix);
}
}