Created
December 30, 2018 12:08
-
-
Save sagar-viradiya/891cf7d08b6ac13bb1fbdc411b76f6a5 to your computer and use it in GitHub Desktop.
Trie data structure in kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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