This post is completed by 1 user

  • 0
Add to List

25. 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 : tttttuuuutorrrriaaaaalllllll
Compressed String : t5u4t1o1r4i1a5l7

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


  • 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 tttttuuuutorrrriaaaaalllllll is : t5u4t1o1r4i1a5l7
Compression of horizonn is : horizonn