Skip to content
EasyStringsNot started

Compress a sensor signal

A field sensor sends a line made of uppercase letters. Compress each consecutive run into its letter followed by the run length. Runs must stay separate when the same letter appears again later.

Input

One line of 1 to 200 uppercase ASCII letters.

Output

One line containing the run-length encoded signal.

Example 1

Input

AAABBCCCCA

Output

A3B2C4A1

Each maximal consecutive run becomes one letter-count pair.

Constraints

  • 1 <= signal length <= 200
  • Only A through Z appear

Hints

Hint 1 of 3

Start the current run with the first character.

Hint 2 of 3

When the next character changes, append the completed pair.

Hint 3 of 3

Remember to append the final run after the loop.

Solution

Show a reference solution and explanation
 Python · reference solution
signal = input().strip()
parts = []
current = signal[0]
count = 1
for char in signal[1:]:
    if char == current:
        count += 1
    else:
        parts.append(current + str(count))
        current = char
        count = 1
parts.append(current + str(count))
print("".join(parts))

Approach

The scan keeps the current symbol and its count. A changed symbol closes one run and starts another; because no later change follows the last run, it is emitted once after the loop.

Your program
signal = input().strip()
parts = []
# compress the runs
print("".join(parts))

Tests: 4 cases including the examples. Run here in Python, JavaScript.

How this page was checked. Reference solutions were checked by the publishing checks. The selector offers only languages runnable in your browser; other reference code is for local use.