Be the first user to complete this post

  • 0
Add to List

String Compression using count of repeated characters - Run Length Encoding

Objective: Write an algorithm to compress the given string by using the count of repeated characters and if new compressed string length is not smaller than the original string then return the original string.


Input String : ssssuuuummmmmmiiiittttttttttttt
Compressed String : s4u4m6i4t13

Input String : Jaain
Compressed String : Jaain (Since compressed string is length is greater than original string)

Input: A String

Output: either A compressed string or original string whichever us smaller.


  • Create a StringBuffer sb, int count
  • Navigate the string taking each character at a time.
  • If you find the same characters increase the count.
  • if not then append the character and its count to the string buffer sb.
  • reset the count value.
  • Compare the length of the compressed String and the original and whichever is the smaller return that string.


Compression of ssssuuuummmmmmiiiittttttttttttt is : s4u4m6i4t13
Compression of Jaain is : Jaain

Also Read: