|
| 1 | +/* |
| 2 | + Definition of a TrieNode: |
| 3 | + |
| 4 | + data class TrieNode( |
| 5 | + var isWord: Boolean = false, |
| 6 | + val children: HashMap<Char, TrieNode> = hashMapOf() |
| 7 | + ) |
| 8 | +*/ |
| 9 | +class Trie { |
| 10 | + val root = TrieNode() |
| 11 | + |
| 12 | + fun insert(word: String) { |
| 13 | + var node = root |
| 14 | + for (c in word.toCharArray()) { |
| 15 | + // For each character in the word, if it's not a child of |
| 16 | + // the current node, create a new TrieNode for that |
| 17 | + // character. |
| 18 | + if (c !in node.children) { |
| 19 | + node.children[c] = TrieNode() |
| 20 | + } |
| 21 | + node = node.children[c]!! |
| 22 | + } |
| 23 | + // Mark the last node as the end of a word. |
| 24 | + node.isWord = true |
| 25 | + } |
| 26 | + |
| 27 | + fun search(word: String): Boolean { |
| 28 | + var node = root |
| 29 | + for (c in word.toCharArray()) { |
| 30 | + // For each character in the word, if it's not a child of |
| 31 | + // the current node, the word doesn't exist in the Trie. |
| 32 | + if (c !in node.children) { |
| 33 | + return false |
| 34 | + } |
| 35 | + node = node.children[c]!! |
| 36 | + } |
| 37 | + // Return whether the current node is marked as the end of the word. |
| 38 | + return node.isWord |
| 39 | + } |
| 40 | + |
| 41 | + fun hasPrefix(prefix: String): Boolean { |
| 42 | + var node = root |
| 43 | + for (c in prefix.toCharArray()) { |
| 44 | + if (c !in node.children) { |
| 45 | + return false |
| 46 | + } |
| 47 | + node = node.children[c]!! |
| 48 | + } |
| 49 | + // Once we've traversed the nodes corresponding to each |
| 50 | + // character in the prefix, return True. |
| 51 | + return true |
| 52 | + } |
| 53 | +} |
0 commit comments