package edu.whu.cs.basic;
import java.util.ArrayList;
public class Trie{
public class TrieNode{
public int path;
public int end;
public TrieNode[] map;
public String word;
public TrieNode() {
super();
this.path = 0;
this.end = 0;
this.map = new TrieNode[26];
this.word = null;
}
}
private TrieNode root;
public Trie(){
root = new TrieNode();
}
public void insert(String word){
if(word == null){
return ;
}
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
int i = 0;
while(i<chs.length){
index = chs[i] - 'a';
if(node.map[index] == null){
node.map[index] = new TrieNode();
if(node.word == null){
node.map[index].word = String.valueOf(chs[i]);
}else{
node.map[index].word = node.word + chs[i];
}
}
node = node.map[index];
node.path++;
i++;
}
node.end ++;
}
public void delete(String word){
if(search (word)){
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for(int i=0;i<chs.length;i++){
index = chs[i] - 'a';
if(node.map[index].path-- == 1){
node.map[index] = null;
}
node = node.map[index];
node.path++;
}
node.end --;
}
}
public boolean search(String word) {
if(word == null){
return false;
}
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for(int i=0;i<chs.length;i++){
index = chs[i] - 'a';
if(node.map[index] == null){
return false;
}
node = node.map[index];
}
return node.end != 0;
}
public int prefixNumber(String pre) {
if(pre == null){
return 0;
}
char[] chs = pre.toCharArray();
TrieNode node = root;
int index = 0;
for(int i=0;i<chs.length;i++){
index = chs[i] - 'a';
if(node.map[index] == null){
return 0;
}
node = node.map[index];
}
return node.path;
}
public void output(TrieNode node,ArrayList<String> list){
if(node != null){
int counts = node.end;
while(counts != 0){
list.add(node.word.toString());
counts--;
}
for(int i=0;i<node.map.length;i++){
output(node.map[i],list);
}
}
}
public static void main(String[] args) {
String[] str = { "zbdfasd",
"zbcfd",
"zbcdfdasfasf",
"abcdaf",
"defdasfa",
"fedfasfd",
"dfdfsa",
"dfdfsa",
"dfdfsa",
"dfdfsa",
"dfdfsa",
"dadfd",
"dadfd",
"dadfd",
"abcfdfa",
"fbcdfd",
"abcdaf"
};
Trie trie = new Trie();
for(int i=0;i<str.length;i++){
trie.insert(str[i]);
}
ArrayList<String> list = new ArrayList<String>();
trie.output(trie.root, list);
for(int i=0;i<list.size();i++)
System.out.println(list.get(i));
}
}