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

  1. Track current character and count
  2. When character changes, append to result
  3. Don't forget the last group

Related Strings exercises

Practice all Strings exercises · Run this idea in the Java compiler