Skip to content

Instantly share code, notes, and snippets.

@arknave
Created April 15, 2016 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arknave/5c2f14b651425ec24c4604f2c671760e to your computer and use it in GitHub Desktop.
Save arknave/5c2f14b651425ec24c4604f2c671760e to your computer and use it in GitHub Desktop.
public class Trie {
final static int ALPHABET_SIZE = 26;
Trie[] children;
public Trie() {
this.children = new Trie[ALPHABET_SIZE];
}
// return true if the word added is new.
public boolean insert(String s) {
if (s == null || s.equals("")) {
return false;
}
final int index = s.charAt(0) - 'a';
if (index < 0 || index >= ALPHABET_SIZE) {
throw new IllegalArgumentException("String contains characters outside the range [a-z]");
}
if (children[index] != null) {
return children[index].insert(s.substring(1));
} else {
children[index] = new Trie();
children[index].insert(s.substring(1));
return true;
}
}
public boolean contains(String word) {
if (word == null) {
return false;
}
if (word.equals("")) {
return true;
} else {
final int index = word.charAt(0) - 'a';
if (children[index] == null) {
return false;
} else {
final String tail = word.substring(1);
return children[index].contains(tail);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment