Skip to content

Instantly share code, notes, and snippets.

@xpcoffee
Last active August 29, 2015 14:10
Show Gist options
  • Save xpcoffee/b4535374646b4cb60ade to your computer and use it in GitHub Desktop.
Save xpcoffee/b4535374646b4cb60ade to your computer and use it in GitHub Desktop.
simple dictionary using radix tree
import java.util.LinkedList;
/**
* Implements a dictionary using a radix tree.
*/
public class AmazonDictionary
{
/* member variables */
private Node root = new Node();
/* tester function */
public static void main(String[] args)
{
AmazonDictionary dict = new AmazonDictionary();
/* valid input */
dict.put("card");
dict.put("carnival");
dict.put("carnivore");
dict.put("care");
/* valid output */
dict.printWords("car"); // words in tree
System.out.println();
dict.printWords("carry"); // no words in tree
System.out.println();
/* invalid input */
System.out.println("Testing invalid input - should throw.");
//dict.put("c.rd");
dict.printWords("c.rd");
System.out.println("Should not appear.");
}
/* API */
public AmazonDictionary()
{ }
public void put(String newWord)
{
Node current = root;
for(char c : newWord.toCharArray()) {
/* check input */
int index = (int) c - (int) 'a';
if ((index < 0) || (index > 26))
throw new java.lang.ArrayIndexOutOfBoundsException("Invalid character input.");
/* create new node if needed */
if(current.next[index] == null)
current.next[index] = new Node();
/* move to that node */
current = current.next[index];
}
current.endword = true;
}
public LinkedList<String> getWords(String base)
{
LinkedList<String> list = new LinkedList<String>();
Node current = root;
/* iterate to get to base */
for(char c : base.toCharArray()) {
int index = (int) c - (int) 'a';
if ((index < 0) || (index > 26))
throw new java.lang.ArrayIndexOutOfBoundsException("Invalid character input.");
/* base not found */
if (current.next[index] == null) return null;
current = current.next[index];
}
/* get words stemming from base */
StringBuilder sb = new StringBuilder(base);
search(current, sb, list);
return list;
}
public void printWords(String base)
{
LinkedList<String> list = getWords(base);
System.out.print("Words that start with " + base + ": ");
if (list == null) {
System.out.println("0");
return;
}
System.out.println(list.size());
System.out.println("The words are: ");
for (String str : list)
System.out.println(str);
}
/* private methods */
private void search(Node x, StringBuilder sb, LinkedList<String> list)
{
/* found complete word */
if(x.endword) list.push(sb.toString());
/* iterate through children */
for(int i = 0; i < 26; i++) {
if(x.next[i] == null) continue;
StringBuilder copy = new StringBuilder(sb);
char c = (char) (i + (int) 'a');
copy.append(c);
search(x.next[i], copy, list);
}
}
/* private classes */
private class Node
{
private Node[] next = new Node [26];
private boolean endword = false;
public Node()
{ }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment