Skip to content

Run-length encoding

Run-length encoding

Compress a string by replacing each run of the same character with that character followed by how many times it repeats: aaabbca3b2c1. Always write the count, even when it is 1.

Walk the string tracking the current character and how long its run is. When the next character differs, write out the run (character + count) and start a fresh run. Don't forget to write the last run after the loop ends.

Log in or create account

IGCSE & A-Level