Last active
November 10, 2015 16:41
-
-
Save fancellu/28b844bbc335146843a6 to your computer and use it in GitHub Desktop.
Compression for HackerRank
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
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 |
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
// 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