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 compressed String and original and whichever is smaller return that string.
Compression of ssssuuuummmmmmiiiittttttttttttt is : s4u4m6i4t13 Compression of Jaain is : Jaain
Top Companies Interview Questions..-
If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.