Matsushita's Blog

Compress a String


Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the string would not become smaller than the original string, your method should return the original string.

How to Solve

By checking the count of repeated characters, I can perform the compressed string. But, it is not better to use string = string + addString. That is because, this code is that the object is copied at every time. String of Java is immutable. So, runtime is too large. Therefore instead of using "String Connection", By using String Buffer Class, I can perform the string efficiently.

Source Code