Skip to content

Instantly share code, notes, and snippets.

@dirkgr
Created October 8, 2016 01:43
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 dirkgr/0f476d89466a105171f25afa3d11857a to your computer and use it in GitHub Desktop.
Save dirkgr/0f476d89466a105171f25afa3d11857a to your computer and use it in GitHub Desktop.
object SuffixTree extends App {
case class TreeNode(children: Map[Char, TreeNode] = Map.empty, end: Boolean = false) {
def addString(string: CharSequence): TreeNode = {
if(string.length() == 0) {
this.copy(end = true)
} else {
val c = string.charAt(0)
val existingNode = children.getOrElse(c, TreeNode())
this.copy(children = children.updated(c, existingNode.addString(string.subSequence(1, string.length()))))
}
}
def print(indent: Int = 0): Unit = {
val indentString = List.fill(indent)(' ').mkString
children.foreach { case (char, node) =>
val endString = if(node.end) "$" else ""
println(s"$indentString$char$endString")
node.print(indent + 1)
}
}
}
def naiveConstruction(string: CharSequence): TreeNode = {
val suffixes = (0 to string.length()).map(string.subSequence(_, string.length()))
suffixes.foldLeft(TreeNode()) { case (rootNode, s) => rootNode.addString(s) }
}
val testString = "babas"
val result = naiveConstruction(testString)
result.print()
}
object UkkonenSuffixTree extends App {
trait State {
def suffixLink: State
def links: Map[Char, State]
}
case class RealState(links: Map[Char, State], suffixLink: State)
class BottomState extends State {
override def suffixLink = ???
override val links = Map('∑' -> RealState(Map.empty, this))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment