0
0
JavaProgramBeginner · 2 min read

Java Program to Compress String Using Character Count

You can compress a string in Java by counting consecutive repeated characters and appending the character followed by its count using a loop, like for (int i = 0; i < s.length(); i++) { count repeats and append char + count }.
📋

Examples

Inputaaabbc
Outputa3b2c1
Inputabcd
Outputa1b1c1d1
Input
Output
🧠

How to Think About It

To compress a string, look at each character one by one and count how many times it repeats in a row. When the character changes, write down the character and the count. Repeat this until the end of the string.
📐

Algorithm

1
Get the input string.
2
Initialize an empty result string and a count variable to 1.
3
Loop through the string characters from the first to the last.
4
If the current character is the same as the next one, increase the count.
5
If it is different or at the end, append the character and count to the result and reset count to 1.
6
Return the compressed result string.
💻

Code

java
public class StringCompressor {
    public static String compress(String s) {
        if (s == null || s.isEmpty()) return "";
        StringBuilder result = new StringBuilder();
        int count = 1;
        for (int i = 0; i < s.length(); i++) {
            if (i + 1 < s.length() && s.charAt(i) == s.charAt(i + 1)) {
                count++;
            } else {
                result.append(s.charAt(i)).append(count);
                count = 1;
            }
        }
        return result.toString();
    }

    public static void main(String[] args) {
        System.out.println(compress("aaabbc"));
        System.out.println(compress("abcd"));
        System.out.println(compress(""));
    }
}
Output
a3b2c1 a1b1c1d1
🔍

Dry Run

Let's trace the string "aaabbc" through the code

1

Start with first character 'a'

count = 1, next char is 'a' same as current, count becomes 2

2

Second 'a'

next char is 'a' same as current, count becomes 3

3

Third 'a'

next char is 'b' different, append 'a3' to result, reset count to 1

4

First 'b'

next char is 'b' same, count becomes 2

5

Second 'b'

next char is 'c' different, append 'b2' to result, reset count to 1

6

First 'c'

no next char, append 'c1' to result

CharacterCountActionResult So Far
a1->2->3Next char same, count increment
a3Next char different, append 'a3'a3
b1->2Next char same, count incrementa3
b2Next char different, append 'b2'a3b2
c1No next char, append 'c1'a3b2c1
💡

Why This Works

Step 1: Counting consecutive characters

The code counts how many times each character repeats in a row using a loop and a count variable.

Step 2: Appending character and count

When the next character is different or the string ends, it adds the current character and its count to the result.

Step 3: Using StringBuilder for efficiency

StringBuilder is used to build the result string efficiently instead of creating many new strings.

🔄

Alternative Approaches

Using recursion
java
public class StringCompressor {
    public static String compressRec(String s) {
        if (s == null || s.isEmpty()) return "";
        return compressHelper(s, 0, 1, new StringBuilder());
    }

    private static String compressHelper(String s, int index, int count, StringBuilder result) {
        if (index == s.length() - 1) {
            result.append(s.charAt(index)).append(count);
            return result.toString();
        }
        if (s.charAt(index) == s.charAt(index + 1)) {
            return compressHelper(s, index + 1, count + 1, result);
        } else {
            result.append(s.charAt(index)).append(count);
            return compressHelper(s, index + 1, 1, result);
        }
    }

    public static void main(String[] args) {
        System.out.println(compressRec("aaabbc"));
    }
}
Recursion can be elegant but may use more memory and be slower for very long strings.
Using Java 8 Streams (less straightforward)
java
import java.util.stream.*;
public class StringCompressor {
    public static String compressStream(String s) {
        if (s == null || s.isEmpty()) return "";
        StringBuilder result = new StringBuilder();
        int[] count = {1};
        IntStream.range(0, s.length()).forEach(i -> {
            if (i + 1 < s.length() && s.charAt(i) == s.charAt(i + 1)) {
                count[0]++;
            } else {
                result.append(s.charAt(i)).append(count[0]);
                count[0] = 1;
            }
        });
        return result.toString();
    }

    public static void main(String[] args) {
        System.out.println(compressStream("aaabbc"));
    }
}
Streams can be used but are less intuitive for this task and require mutable state.

Complexity: O(n) time, O(n) space

Time Complexity

The program loops through the string once, so time grows linearly with input size.

Space Complexity

The output string can be up to twice the input length in worst case (each char followed by count), so space is O(n).

Which Approach is Fastest?

The iterative approach with StringBuilder is fastest and simplest; recursion adds overhead, streams add complexity.

ApproachTimeSpaceBest For
Iterative with StringBuilderO(n)O(n)Simple and efficient for all inputs
RecursiveO(n)O(n)Elegant but less efficient for large strings
Java StreamsO(n)O(n)Modern style but less clear and more complex
💡
Use StringBuilder to build the compressed string efficiently inside loops.
⚠️
Forgetting to append the last character and its count after the loop ends.