|
| 1 | +class Trie() { |
| 2 | + |
| 3 | + /** Initialize your data structure here. */ |
| 4 | + case class TrieNode(isKey: Boolean = false, children: Array[Option[TrieNode]] = Array.fill[Option[TrieNode]](26)(None)) |
| 5 | + |
| 6 | + val data: TrieNode = TrieNode() |
| 7 | + |
| 8 | + private def getCharIndex(char: Char): Int = char.toInt - 97 |
| 9 | + |
| 10 | + /** Inserts a word into the trie. */ |
| 11 | + def insert(word: String): Unit = recursiveInsert(data, word) |
| 12 | + |
| 13 | + /** Returns if the word is in the trie. */ |
| 14 | + def search(word: String): Boolean = recursiveSearch(data, word) |
| 15 | + |
| 16 | + /** Returns if there is any word in the trie that starts with the given prefix. */ |
| 17 | + def startsWith(prefix: String): Boolean = recursiveSearch(data, prefix, doSearchPrefix = true) |
| 18 | + |
| 19 | + |
| 20 | + def recursiveInsert(node: TrieNode, text: String): Unit = { |
| 21 | + if (text.nonEmpty) { |
| 22 | + val firstCharIndex = getCharIndex(text.head) |
| 23 | + val childToInsert = node.children(firstCharIndex) match { |
| 24 | + case Some(child) if text.length == 1 => |
| 25 | + val updatedChild = child.copy(isKey = true) |
| 26 | + node.children(firstCharIndex) = Some(updatedChild) |
| 27 | + updatedChild |
| 28 | + case Some(child) => child |
| 29 | + case None => |
| 30 | + val newChild = TrieNode(text.length == 1) |
| 31 | + node.children(firstCharIndex) = Some(newChild) |
| 32 | + newChild |
| 33 | + } |
| 34 | + recursiveInsert(childToInsert, text.tail) |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + def recursiveSearch(node: TrieNode, text: String, doSearchPrefix: Boolean = false): Boolean = { |
| 39 | + if (text.isEmpty) |
| 40 | + if (doSearchPrefix) true else node.isKey |
| 41 | + else { |
| 42 | + val firstCharIndex = getCharIndex(text.head) |
| 43 | + node.children(firstCharIndex) match { |
| 44 | + case Some(child) => recursiveSearch(child, text.tail, doSearchPrefix) |
| 45 | + case None => false |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments