Show problems as
Classic problem #3163MediumString

String Compression III

Real-world version: Shorthand for a Run of Marks
Tracked in this browser only
Read String Compression III on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A tape of lowercase letters reads tape. Write its shorthand by repeating the following until nothing is left of the tape: take off the longest stretch at the front made of one repeated letter, but never more than nine of it, and append to the shorthand how many were taken followed by that letter.

Return the shorthand.

Examples

Example 1

Input
tape = "aabbaa"
Output
"2a2b2a"

Three stretches of two letters each, so each is written as its count followed by its letter.

Example 2

Input
tape = "aaaaaaaaaa"
Output
"9a1a"

Ten of the same letter, but a stretch may hold at most nine, so nine come off first and the last one follows as a stretch of its own.

Example 3

Input
tape = "a"
Output
"1a"

A single letter is a stretch of one.

Constraints

  • 1 <= tape.length <= 2 * 10^5
  • The tape is made of lowercase English letters.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def compressed_string(tape: str) -> str:
Java
public String compressedString(String tape)