← Coding round practice

Run-Length Encoding

MediumApp Logic (real-world)

The problem

Compress a string by replacing runs of the same character with the character followed by its count — a basic compression scheme.

Sample input

aaabbbcccd

Sample output

a3b3c3d1
Show the solution · 8 languages
fun main() {
    val s = "aaabbbcccd"
    val result = StringBuilder()
    var i = 0
    while (i < s.length) {
        var count = 1
        while (i + 1 < s.length && s[i] == s[i + 1]) {
            count++
            i++
        }
        result.append(s[i]).append(count)
        i++
    }
    println(result.toString())
}