Skip to content

Instantly share code, notes, and snippets.

@sagar-viradiya
Created December 30, 2018 12:08
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagar-viradiya/891cf7d08b6ac13bb1fbdc411b76f6a5 to your computer and use it in GitHub Desktop.
Save sagar-viradiya/891cf7d08b6ac13bb1fbdc411b76f6a5 to your computer and use it in GitHub Desktop.
Trie data structure in kotlin
class Trie {
data class Node(var word: String? = null, val childNodes: MutableMap<Char, Node> = mutableMapOf())
private val root = Node()
fun insert(word: String) {
var currentNode = root
for (char in word) {
if (currentNode.childNodes[char] == null) {
currentNode.childNodes[char] = Node()
}
currentNode = currentNode.childNodes[char]!!
}
currentNode.word = word
}
fun search(word: String): Boolean {
var currentNode = root
for (char in word) {
if (currentNode.childNodes[char] == null) {
return false
}
currentNode = currentNode.childNodes[char]!!
}
return currentNode.word != null
}
fun startsWith(word: String): Boolean {
var currentNode = root
for (char in word) {
if (currentNode.childNodes[char] == null) {
return false
}
currentNode = currentNode.childNodes[char]!!
}
return currentNode.word == null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment