Last active
April 7, 2016 04:36
-
-
Save rafbarr/5ae7ba595d98b0e0e7ee to your computer and use it in GitHub Desktop.
This file contains hidden or 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
case class SimplePrefixTree(prefix: String, leaves: Seq[SimplePrefixTree]) | |
object SimplePrefixTree { | |
def apply(stringSet: Set[String]): SimplePrefixTree = { | |
val longestCommonPrefix = if (!stringSet.isEmpty) { | |
(stringSet.min, stringSet.max).zipped.takeWhile(v => v._1 == v._2).unzip._1.mkString | |
} else { | |
"" | |
} | |
if (longestCommonPrefix.isEmpty) { | |
val leaves = stringSet | |
.filter(!_.isEmpty) | |
.groupBy(_.charAt(0).toString) | |
.values | |
.map(SimplePrefixTree(_)) | |
.toSeq | |
SimplePrefixTree("", leaves) | |
} else { | |
val remainingStrSet = stringSet.map(_.stripPrefix(longestCommonPrefix)).filter(!_.isEmpty) | |
if (remainingStrSet.isEmpty) { | |
SimplePrefixTree(longestCommonPrefix, Seq()) | |
} else { | |
SimplePrefixTree(longestCommonPrefix, Seq(SimplePrefixTree(remainingStrSet))) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment