Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active August 29, 2015 14:21
Show Gist options
  • Save charlespunk/eeffce99540fd8f00d1a to your computer and use it in GitHub Desktop.
Save charlespunk/eeffce99540fd8f00d1a to your computer and use it in GitHub Desktop.
class TrieNode {
// Initialize your data structure here.
private Map<Character, TrieNode> children;
private boolean isWord;
public TrieNode() {
this.children = new HashMap<>();
}
TrieNode addLetter(Character letter) {
if (!children.containsKey(letter)) {
children.put(letter, new TrieNode());
}
return children.get(letter);
}
TrieNode getChild(Character letter) {
return children.get(letter);
}
void setIsWord() {
isWord = true;
}
boolean isWord() {
return isWord;
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
currentNode = currentNode.addLetter(word.charAt(i));
}
currentNode.setIsWord();
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
currentNode = currentNode.getChild(word.charAt(i));
if (currentNode == null) {
return false;
}
}
return currentNode.isWord();
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode currentNode = root;
for (int i = 0; i < prefix.length(); i++) {
currentNode = currentNode.getChild(prefix.charAt(i));
if (currentNode == null) {
return false;
}
}
return true;
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment