Last active
March 9, 2019 04:59
-
-
Save psilospore/9bddd8682d68578cebce664441895047 to your computer and use it in GitHub Desktop.
Bad Scala Trie
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
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