Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

String Compression using count of repeated characters — Run Length Encoding

Objec­tive: Write an algo­rithm to com­press the given string by using the count of repeated char­ac­ters and if new com­pressed string length is not smaller than the orig­i­nal string then return the orig­i­nal string.

Exam­ple:

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

Out­put: either A com­pressed string or orig­i­nal string whichever us smaller.

Approach:

  • Cre­ate a String­Buffer sb, int count
  • Nav­i­gate the string tak­ing each char­ac­ter at a time.
  • If you find the same char­ac­ters increase the count.
  • if not then append the char­ac­ter and its count to the string buffer sb.
  • reset the count value.
  • Com­pare the length of com­pressed String and orig­i­nal and whichever is smaller return that string.

Com­plete Code:


Out­put:

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

You may also like...