String Compression in Java: Solution, Explanation & Practice
Compress string using counts of repeated characters
Problem summary
Write a program that compresses a string by replacing consecutive repeated characters with the character followed by count.
Starter code
public class Main {
public static void main(String[] args) {
String text = "aaabbbccc"; // Test case 1
// Compress: consecutive chars -> char + count
// Print: Compressed: <result>
}
}Expected output and test cases
- Compress aaabbbccc
Compressed: a3b3c3
- Compress aabcccc
Compressed: a2b1c4
- No compression needed
Compressed: a1b1c1
Hints
- Track current character and count
- When character changes, append to result
- Don't forget the last group
Validated solution
Reveal Java solution
public class Main {
static String compress(String text) {
if (text.isEmpty()) return "";
StringBuilder result = new StringBuilder();
int run = 1;
for (int i = 1; i <= text.length(); i++) {
if (i < text.length() && text.charAt(i) == text.charAt(i - 1)) run++;
else { result.append(text.charAt(i - 1)).append(run); run = 1; }
}
return result.toString();
}
public static void main(String[] args) {
System.out.println("Compressed: " + compress("aaabbbccc"));
}
}How to approach the problem
Run-length encoding needs a count for the current group. The loop deliberately reaches length so the final group is flushed by the same branch that flushes earlier groups.
Approach
- Handle an empty String before reading character zero.
- Grow a run while neighboring characters match.
- Append the previous character and count when a run ends.
Time and space complexity
Time: O(n). Space: O(n).
Edge cases to test
- One character compresses to that character plus 1.
- A compressed representation can be longer than the original.
Common mistakes
- Forgetting to append the final run.
- Resetting the count before appending it.
Follow-up challenge
Return the original text when compression does not save space.
Related Strings exercises
- Practice Remove All Spaces in Java
- Practice Character Frequency in Java
- Practice Alphabetical Character Frequency in Java
Practice all Strings exercises · Run this idea in the Java compiler