1.6 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).
public static String compress(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ) {
int j = i + 1;
char curr = s.charAt(i);
while (j < s.length() && s.charAt(j) == curr) ++j;
int count = j - i;
sb.append(curr+String.valueOf(count));
i = j;
}
return sb.length() < s.length() ? sb.toString() : s;
}