Java Tries with Array Char
1. insert(TNode r, String s, Int inx)
- insert s to tries
2. contains(TNode r, String s, Int inx)
- check whether tries contains s or not
3. ArrayList< String> getList(TNode r, String input, List list)
- check get suffix list from tries r
3. ArrayList< String> autoComplete(TNode r, String input, List list)
- return the longest string contains input as suffix
4. countPath(TNode r)
- count the all the paths from root to leaf node
// Tries2.java
// better version: http://localhost/html/indexTriesDataStructure.html
// another tries data structure again!
// add: count all the longest paths
class TNode{
boolean isWord;
String word;
TNode[] arr = new TNode[26];
// use Map map;
public TNode(){
isWord = false;
}
}
public class Tries2{
public static void main(String[] args) {
// a | b | c |
// d |
// e f |
test0();
test1();
}
public static void test0(){
Aron.beg();
TNode r = new TNode();
String s = "a";
String s1 = "ab";
String s2 = "abc";
String s3 = "abd";
String s4 = "aef";
int inx = 0;
insert(r, s, inx);
insert(r, s1, inx);
insert(r, s2, inx);
insert(r, s3, inx);
insert(r, s4, inx);
Print.pb(contains(r, "a", inx) == true);
Print.pb(contains(r, "ac", inx) == false);
Print.pb(contains(r, "ab", inx) == true);
Print.pb(contains(r, "abc", inx) == true);
int count = countPath(r);
Print.pb(count);
Aron.end();
}
public static void test1(){
Aron.beg();
TNode r = new TNode();
String s = "a";
String s1 = "ab";
String s2 = "abc";
String s3 = "abd";
String s4 = "aef";
int inx = 0;
insert(r, s, inx);
insert(r, s1, inx);
insert(r, s2, inx);
insert(r, s3, inx);
insert(r, s4, inx);
String input = "ab";
List list = autoComplete(r, input, inx);
Print.pb(list);
Aron.end();
}
public static void insert(TNode r, String s, int inx){
if (inx < s.length()){
int index = s.charAt(inx) - 'a';
if(r.arr[index] == null)
r.arr[index] = new TNode();
insert(r.arr[index], s, inx + 1);
}else{
r.word = s;
r.isWord = true;
}
}
public static boolean contains(TNode r, String s, int inx){
if(inx < s.length()){
int index = s.charAt(inx) - 'a';
if(r.arr[index] != null){
return contains(r.arr[index], s, inx+1);
}else{
return false;
}
}else{
return r.isWord;
}
}
/*
Count the number of paths of Tries
Input Tries
Return number of paths or number of words in Tries
Count the number of longest paths in Tries
*/
public static int countPath(TNode r){
if(r != null){
int s = 0;
int i = 0;
for(i=0; i list){
if(r != null){
int c = 0;
for(int i=0; i autoComplete(TNode r, String s, int inx){
if (inx < s.length()){
int index = s.charAt(inx) - 'a';
if(r.arr[index] != null){
return autoComplete(r.arr[index], s, inx + 1);
}else{
return new ArrayList();
}
}else{
List list = new ArrayList();
getList(r, list);
return list;
}
}
}