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
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))
const signal = readline();
const parts = [];
let current = signal[0];
let count = 1;
for (const char of signal.slice(1)) {
if (char === current) count++;
else { parts.push(current + count); current = char; count = 1; }
}
parts.push(current + count);
console.log(parts.join(''));
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.