1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| class TrieNode { val children = HashMap<Char, TrieNode>() var isWord = false }
class Trie { private val root = TrieNode()
fun insert(word: String) { var node = root for (char in word) { if (!node.children.containsKey(char)) { node.children[char] = TrieNode() } node = node.children[char]!! } node.isWord = true }
fun search(word: String): Boolean { var node = root for (char in word) { if (!node.children.containsKey(char)) { return false } node = node.children[char]!! } return node.isWord }
fun startsWith(prefix: String): Boolean { var node = root for (char in prefix) { if (!node.children.containsKey(char)) { return false } node = node.children[char]!! } return true } }
|