Skip to content

Instantly share code, notes, and snippets.

@shankarshastri
Created August 11, 2020 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shankarshastri/43c8c0085cd85f1aef3d095c36131f9e to your computer and use it in GitHub Desktop.
Save shankarshastri/43c8c0085cd85f1aef3d095c36131f9e to your computer and use it in GitHub Desktop.
Trie
import scala.annotation.tailrec
import scala.collection.immutable.HashMap
case class TrieNode(h: HashMap[Char, TrieNode], isWord: Boolean = false)
object TrieNode {
def empty = TrieNode(HashMap.empty)
def buildTrieNode(s: List[Char], t: TrieNode = TrieNode.empty): TrieNode = {
s match {
case Nil => t.copy(isWord = true)
case ::(head, next) =>
t.h.get(head) match {
case Some(value) =>
t.copy(t.h.updated(head, buildTrieNode(next, value)))
case None =>
t.copy(t.h.updated(head, buildTrieNode(next)))
}
}
}
@tailrec
def search(l: List[Char], t: TrieNode,
isPrefix: Boolean = false): Boolean = {
l match {
case head :: Nil =>
t.h.get(head) match {
case Some(value) if value.isWord || isPrefix =>
search(Nil, value, isPrefix)
case _ =>
println(head)
false
}
case ::(head, next) =>
t.h.get(head) match {
case Some(value) =>
println(value)
search(next, value, isPrefix)
case None =>
false
}
case Nil => true
}
}
def constructFromListOfString(l: List[String],
t: TrieNode = TrieNode.empty): TrieNode = {
def cHelper(l: List[String], trie: TrieNode): TrieNode = {
l.foldLeft(trie)((a,b) => buildTrieNode(b.toList, a))
}
cHelper(l, t)
}
}
TrieNode.constructFromListOfString(List("tea"))
TrieNode.search("ten".toList, TrieNode.constructFromListOfString(List("tea", "ted", "tennis")), isPrefix = true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment