KatInterview

Expand a Compact Letter-and-Count String

StringsAuto-graded · 23 test cases
MediumAuto-gradedStringsstring-parsingtwo-pointerssimulation

Last updated

Parse a string of letters with optional multi-digit repeat counts, treating a missing count as one, and rebuild the expanded text in a single left-to-right pass.

Expand a Compact Letter-and-Count String

A text made of lowercase letters was shrunk into a compact form. In this form, every letter is optionally followed by a number saying how many times that letter should appear. If the number is left out, the letter appears exactly once. For instance, a5b3c expands to aaaaabbbc.

Write a function that takes the compact string and returns the fully expanded text.

Rules

  • The input is a series of tokens. Each token is a single lowercase letter, optionally followed by a count.
  • A count is a sequence of one or more decimal digits. It never begins with 0 and its value is at least 1. Counts may span several digits, so a12 means twelve copies of a.
  • A token with no count produces one copy of its letter. A token with count c produces c copies.
  • Process the tokens from left to right and concatenate what they produce.
  • Neighbouring tokens may share the same letter. Each token is expanded independently, with no merging.
  • The input is always valid under these rules.

Constraints

  • 1 <= len(s) <= 10^4
  • s consists only of lowercase English letters and the digits 0-9, and its first character is a letter.
  • Every count satisfies 1 <= count <= 10^5.
  • The expanded string has length at most 10^5.

Examples

Example 1

Input: expand_compact_string('a5b3c')

Output: 'aaaaabbbc'

Example 2

Input: expand_compact_string('q10e')

Output: 'qqqqqqqqqqe'

Example 3

Input: expand_compact_string('ab2a')

Output: 'abba'

Hints

Hint 1

Every token starts with a letter, so whenever you stand on a letter you know a new token begins there.

Hint 2

After reading a letter, keep moving a second index forward while the characters are digits. The whole slice of digits is the count, not just one digit.

Hint 3

If no digits followed the letter, use a count of 1. Collect the pieces in a list and join them once at the end instead of concatenating repeatedly.