A logging tool shortens strings by replacing each run of the same letter with the letter followed by the run length: aaabcc becomes a3b1c2. If the compressed form is not shorter than the original, print the original instead.
Write it in Java using StringBuilder (repeated += on a String inside a loop is the mistake interviewers look for).
Constraints
- 1 ≤ length ≤ 100000
Input and output
- Input
- One line: a string of lowercase letters.
- Output
- The compressed string, or the original if compression does not help.
Examples
Input 1
aaabcccccOutput
a3b1c5a3 b1 c5 gives "a3b1c5", 6 characters instead of 9.
Input 2
abcOutput
abc"a1b1c1" would be longer, so the original is printed.
Show hints
- Walk the string once, counting how long the current run is.
- Append to a StringBuilder when the run ends.
Show the explanation
Scan once with a run counter; when the next character differs (or the string ends), append the letter and the count to a StringBuilder. String is immutable, so s = s + x in a loop copies the whole string every time — O(n²) overall — while StringBuilder.append is amortised O(1). Compare lengths at the end and return the shorter.
Original UniCircle question. Last reviewed 22 Oct 2026.
