Problem · String

Run-Length String Compression

Learn this problem
EasySalesforce logoSalesforceFULLTIMEOA
See Salesforce hiring insights

Problem statement

Given a string s, compress each maximal group of consecutive equal characters.

  • Append the group's character once.
  • If the group contains more than one character, append its full length in base 10.
  • If the group contains exactly one character, do not append a count.

Return the compressed string.

Function

compressString(s: String) → String

Examples

Example 1

s = "aaaabeee"return = "a4be3"

The groups are aaaa, b, and eee. Their encodings are a4, b, and e3.

Example 2

s = "a"return = "a"

The only group has length 1, so no count is appended.

Example 3

s = "abbbbbbbbbbbb"return = "ab12"

The first group contributes a. The following group contains 12 copies of b, so it contributes b12.

Constraints

  • 1 <= s.length <= 2000
  • s contains letters, digits, or symbols.

More Salesforce problems

drafts saved locally
public String compressString(String s) {
    // Write your code here.
}
s"aaaabeee"
expected"a4be3"
checking account