|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +public class Trie { |
| 4 | + private TrieNode root; |
| 5 | + |
| 6 | + public Trie() { |
| 7 | + this.root = new TrieNode(); |
| 8 | + } |
| 9 | + |
| 10 | + /** |
| 11 | + * Insert a word into the trie. |
| 12 | + * |
| 13 | + * @param word The word to insert. |
| 14 | + */ |
| 15 | + public void insert(String word) { |
| 16 | + Map<Character, TrieNode> children = root.children; |
| 17 | + |
| 18 | + for (int i = 0; i < word.length(); i++) { |
| 19 | + TrieNode node; |
| 20 | + char c = word.charAt(i); |
| 21 | + |
| 22 | + if (children.containsKey(c)) { |
| 23 | + node = children.get(c); |
| 24 | + } else { |
| 25 | + /** |
| 26 | + * At this point, we know if we couldn't find word.charAt(i) in our trie, |
| 27 | + * the word doesn't exist. Create a new TrieNode and populate it's child. |
| 28 | + */ |
| 29 | + node = new TrieNode(); |
| 30 | + children.put(c, node); |
| 31 | + } |
| 32 | + |
| 33 | + children = node.children; |
| 34 | + } |
| 35 | + |
| 36 | + // Once we've reached the end of the word, mark the node as a leaf. |
| 37 | + node.endOfWord = true; |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Lookup a word in the trie. |
| 42 | + * |
| 43 | + * @param word The word to lookup. |
| 44 | + * @return True if the trie structure contains the word. |
| 45 | + */ |
| 46 | + public boolean lookup(String word) { |
| 47 | + Map<Character, TrieNode> children = root.children; |
| 48 | + |
| 49 | + /** |
| 50 | + * For each letter in the word, traverse to the deepest child found. |
| 51 | + */ |
| 52 | + for (int i = 0; i < word.length(); i++) { |
| 53 | + TrieNode node; |
| 54 | + char c = word.charAt(i); |
| 55 | + |
| 56 | + if (children.containsKey(c)) { |
| 57 | + node = children.get(c); |
| 58 | + children = node.children; |
| 59 | + } else { |
| 60 | + /* If at any point a character in the word isn't found, return false as the word doesn't exist. */ |
| 61 | + return false; |
| 62 | + } |
| 63 | + } |
| 64 | + return true; |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Each node contains a hashmap of children nodes. |
| 69 | + */ |
| 70 | + static class TrieNode { |
| 71 | + Map<Character, TrieNode> children; |
| 72 | + boolean endOfWord; |
| 73 | + |
| 74 | + public TrieNode() { |
| 75 | + this.children = new HashMap<>(); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | +} |
0 commit comments