Skip to content

Instantly share code, notes, and snippets.

@psilospore
Last active March 9, 2019 04:59
Show Gist options
  • Save psilospore/9bddd8682d68578cebce664441895047 to your computer and use it in GitHub Desktop.
Save psilospore/9bddd8682d68578cebce664441895047 to your computer and use it in GitHub Desktop.
Bad Scala Trie
import scala.collection.mutable
class TrieNode(var children: mutable.Map[Char, TrieNode] = mutable.Map()) {
// Inserts into current Trie
def insert(c: Char): TrieNode = {
children.get(c).getOrElse({
children.put(c, new TrieNode())
this
}
)
}
}
class Trie() {
/** Initialize your data structure here. */
val trie = new TrieNode()
/** Inserts a word into the trie. */
def insert(word: String) = {
var currentTrie = trie
for {
c <- word
} {
currentTrie = currentTrie.children.get(c).getOrElse(new TrieNode())
currentTrie.insert(c)
}
}
/** Returns if the word is in the trie. */
def search(word: String): Boolean = {
var currentTrie = Option(trie)
(for {
c <- word
} yield {
currentTrie = currentTrie.map(_.children(c))
currentTrie
}).flatten.nonEmpty
}
/** Returns if there is any word in the trie that starts with the given prefix. */
def startsWith(prefix: String): Boolean = {
true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment