Created
May 6, 2021 04:40
-
-
Save dragneelfps/4556e24df086bc72033ec61f6fdffc0b 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() { | |
private data class Node(val children: MutableList<Node?> = MutableList(26) { null }, var leaf: Boolean = false) | |
private val root = Node() | |
/** Inserts a word into the trie. */ | |
fun insert(word: String) { | |
var curr = root | |
for(ch in word) { | |
val idx = ch.idx() | |
if(curr.children[idx] == null) { | |
curr.children[idx] = Node() | |
} | |
curr = curr.children[idx]!! | |
} | |
curr.leaf = true | |
} | |
/** Returns if the word is in the trie. */ | |
fun search(word: String): Boolean { | |
var curr = root | |
for(ch in word) { | |
val idx = ch.idx() | |
if(curr.children[idx] == null) { | |
return false | |
} | |
curr = curr.children[idx]!! | |
} | |
return curr.leaf | |
} | |
/** Returns if there is any word in the trie that starts with the given prefix. */ | |
fun startsWith(prefix: String): Boolean { | |
var curr = root | |
for(ch in prefix) { | |
val idx = ch.idx() | |
if(curr.children[idx] == null) { | |
return false | |
} | |
curr = curr.children[idx]!! | |
} | |
return true | |
} | |
private fun Char.idx() = toInt() - 'a'.toInt() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment