Skip to content

Instantly share code, notes, and snippets.

@fancellu
Last active November 10, 2015 16:41
Show Gist options
  • Save fancellu/28b844bbc335146843a6 to your computer and use it in GitHub Desktop.
Save fancellu/28b844bbc335146843a6 to your computer and use it in GitHub Desktop.
Compression for HackerRank
def pack(s:String):List[String]=
if (s.isEmpty()) Nil
else{
val (packed, rest) = s span { _ == s.head }
packed::pack(rest)
}
def rle(s:String)= pack(s).map(e=>(e.head,e.length))
def compress(s:String):String=
rle(s).map{case (ch,len)=>if (len==1) ch else s"$ch$len"}.mkString
compress("aaaaabbbbbbbbbccccpqrstuv")
// a5b9c4pqrstuv
// Another implementation
def compress(s: String): String = {
@scala.annotation.tailrec
def recurse(l: List[(Char, Int)], acc: List[(Char, Int)] = Nil): List[(Char, Int)] = {
val (head@(ch, n)) :: tail = l
tail match {
case Nil => head :: acc
case (`ch`, tailn) :: subtail => recurse((ch, n + tailn) :: subtail, acc)
case _ => recurse(tail, head :: acc)
}
}
val listCharInt=recurse(s.toList.map(_->1))
listCharInt.reverse.map{ case (ch, n) => if (n == 1) ch else s"$ch$n" }.mkString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment