LearnFrenzy
Sign in Take a free test

Strings and StringBuilder · Java String Programs · Question 3

Compress a string with character counts in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Compress strings like "aaabccdddd" to "a3b1c2d4"; return the original string if the compressed version is not shorter.

Solution
Main.java
public class Main {
    static String compress(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); ) {
            char c = s.charAt(i);
            int j = i;
            while (j < s.length() && s.charAt(j) == c) j++;
            sb.append(c).append(j - i);
            i = j;
        }
        return sb.length() < s.length() ? sb.toString() : s;
    }

    public static void main(String[] args) {
        for (String s : new String[]{"aaabccdddd", "abc", "zzzzzzzzzzzz", ""}) System.out.println("[" + s + "] -> [" + compress(s) + "]");
    }
}

Output Verified by compiling and running

[aaabccdddd] -> [a3b1c2d4]
[abc] -> [abc]
[zzzzzzzzzzzz] -> [z12]
[] -> []

An inner while loop finds the end of each run; a StringBuilder collects the result. "abc" would grow to "a1b1c1", so it is returned unchanged.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links