Created
July 26, 2015 17:41
-
-
Save matteogobbi/1f271bac4840c6e2824e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
class TrieNode { | |
char letter; | |
HashMap<Character, TrieNode> children; | |
public TrieNode(char letter) { | |
this.letter = letter; | |
children = new HashMap<Character, TrieNode>(); | |
} | |
public void addChild(TrieNode child) { | |
children.put(child.letter, child); | |
} | |
} | |
public class Trie { | |
private TrieNode root; | |
public Trie() { | |
root = new TrieNode('0'); | |
} | |
// Inserts a word into the trie. | |
public void insert(String word) { | |
TrieNode currentNode = root; | |
for (int i=0; i<word.length(); i++) { | |
char c = word.charAt(i); | |
if (currentNode.children.containsKey(c)) { | |
currentNode = currentNode.children.get(c); | |
} else { | |
TrieNode newNode = new TrieNode(c); | |
currentNode.addChild(newNode); | |
currentNode = newNode; | |
} | |
} | |
currentNode.addChild(new TrieNode('*')); | |
} | |
// Returns if the word is in the trie. | |
public boolean search(String word) { | |
return search(word, false); | |
} | |
// Returns if there is any word in the trie | |
// that starts with the given prefix. | |
public boolean startsWith(String prefix) { | |
return search(prefix, true); | |
} | |
private boolean search(String word, boolean prefix) { | |
TrieNode currentNode = root; | |
for (int i=0; i<word.length(); i++) { | |
char c = word.charAt(i); | |
if (currentNode.children.containsKey(c)) { | |
currentNode = currentNode.children.get(c); | |
} else { | |
return false; | |
} | |
} | |
return prefix || (!prefix && currentNode.children.containsKey('*')); | |
} | |
} | |
// 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