Given a string, replace adjacent, repeated characters with the character followed by the number of repeated occurrences. If the character does not has any adjacent, repeated occurrences, it is not changed.
Assumptions
The string is not null
The characters used in the original string are guaranteed to be ‘a’ - ‘z’
There are no adjacent repeated characters with length > 9
Examples
- “abbcccdeee” → “ab2c3de3”
public String compress(String input) {
if (input.length() < 2) {
return input;
}
StringBuilder sb = new StringBuilder();
int count = 1;
for (int i = 0; i < input.length(); i++) {
if (i + 1 < input.length() && input.charAt(i) == input.charAt(i + 1)) {
count++;
continue;
}
sb.append(input.charAt(i));
if (count > 1) {
sb.append(count);
count = 1;
}
}
return sb.toString();
}