| 11 | } |
| 12 | |
| 13 | public class DesignATrie { |
| 14 | TrieNode root; |
| 15 | |
| 16 | public DesignATrie() { |
| 17 | this.root = new TrieNode(); |
| 18 | } |
| 19 | |
| 20 | public void insert(String word) { |
| 21 | TrieNode node = this.root; |
| 22 | for (char c : word.toCharArray()) { |
| 23 | // For each character in the word, if it's not a child of |
| 24 | // the current node, create a new TrieNode for that |
| 25 | // character. |
| 26 | node.children.putIfAbsent(c, new TrieNode()); |
| 27 | node = node.children.get(c); |
| 28 | } |
| 29 | // Mark the last node as the end of a word. |
| 30 | node.isWord = true; |
| 31 | } |
| 32 | |
| 33 | public boolean search(String word) { |
| 34 | TrieNode node = this.root; |
| 35 | for (char c : word.toCharArray()) { |
| 36 | // For each character in the word, if it's not a child of |
| 37 | // the current node, the word doesn't exist in the Trie. |
| 38 | if (!node.children.containsKey(c)) { |
| 39 | return false; |
| 40 | } |
| 41 | node = node.children.get(c); |
| 42 | } |
| 43 | // Return whether the current node is marked as the end of the |
| 44 | // word. |
| 45 | return node.isWord; |
| 46 | } |
| 47 | |
| 48 | public boolean hasPrefix(String prefix) { |
| 49 | TrieNode node = this.root; |
| 50 | for (char c : prefix.toCharArray()) { |
| 51 | if (!node.children.containsKey(c)) { |
| 52 | return false; |
| 53 | } |
| 54 | node = node.children.get(c); |
| 55 | } |
| 56 | // Once we've traversed the nodes corresponding to each |
| 57 | // character in the prefix, return True. |
| 58 | return true; |
| 59 | } |
| 60 | } |
nothing calls this directly
no outgoing calls
no test coverage detected