FastPrepString Compression

String Compression

Abridge logoAbridge● MediumFULLTIMEOA
Learn

Problem statement

Given a string chars, compress each maximal run of equal consecutive characters.

  • Write the character once.
  • If the run length is greater than one, immediately follow it with the decimal digits of that length.

Return the complete compressed string. Run counts may contain multiple digits.

Function

compress(chars: String) → String

Examples

Example 1

chars = "aabbccc"return = "a2b2c3"

The consecutive runs have lengths 2, 2, and 3.

Example 2

chars = "a"return = "a"

A run of length one has no numeric suffix.

Example 3

chars = "abbbbbbbbbbbb"return = "ab12"

The first run has length one, and the twelve consecutive b characters use the two digits 12.

Constraints

  • 1 <= chars.length <= 100000.
  • chars contains printable ASCII characters other than line breaks.

More Abridge problems

See Abridge hiring insights
public String compress(String chars) {
    // Write your code here.
}
chars"aabbccc"
expected"a2b2c3"
Checking account…