import java.util.ArrayList;
import org.junit.Test;
public class TriNode{
private static final int R=256;
private static final ArrayList<String> keysWithPrefix=new ArrayList<String>();
public static void put(Node x,String word){
if(word.length()==0) return;
for(int i=0;i<word.length();i++){
char key=word.charAt(i);
if(x.next[key]==null){
x.next[key]=new Node();
}
x=x.next[key];
}
x.flag=true;
}
public static void query(Node x,String pre){
for(int i=0;i<pre.length();i++){
char ch=pre.charAt(i);
if(x.next[ch]==null) return;
x=x.next[ch];
}
collect(x,pre);
}
private static void collect(Node x,String pre){
if(x==null) return;
if(x.flag!=false){
keysWithPrefix.add(pre);
}
for(char c=0;c<R;c++){
collect(x.next[c],pre+c);
}
}
static class Node{
private Node[] next=new Node[R];
private boolean flag=false;
}
@Test
public void test(){
Node root=new Node();
String[] text={"by","sea","sell","sells","shell","shells","she","sho"};
for(int i=0;i<text.length;i++){
put(root,text[i]);
}
query(root,"se");
System.out.println(keysWithPrefix);
}
}