String Compression


Implement a method to perform basic string compression using the counts of repeated characters.

For example, the string “aabcccccaaa” would become “a2b1c5a3”. If the “compressed” string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a – z).

My solution is:

GitHub

public class StringCompression {    public static String compress(String input) {     if (input == null) {       return null;     }      StringBuilder output = new StringBuilder();      char prevChar = input.charAt(0);     int lengthSoFar = 1;      for (int index = 1; index < input.length(); index++) {       char currentChar = input.charAt(index);        if (prevChar == currentChar) {         lengthSoFar++;       } else {         output.append(prevChar);         output.append(lengthSoFar);          // reset counters         prevChar = currentChar;         lengthSoFar = 1;       }     }     output.append(prevChar);     output.append(lengthSoFar);      return output.toString().length() <= input.length() ? output.toString() : input;   } }