String Compression in Java: 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
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