/* ---------------------------------------------------------
Compress: turn "aaabbcccc" into "a3b2c4"
This is run-length encoding (RLE)
--------------------------------------------------------- */
fun compress(s: String): String {
if (s.isEmpty()) return "" // Edge case: empty string
val out = StringBuilder() // Result string
var count = 1 // Count of repeated characters
// Start from index 1 and compare with previous character
for (i in 1..s.length) {
// If still repeating the same character, increase count
if (i < s.length && s[i] == s[i - 1]) {
count++
} else {
// Character changed OR reached end of string
out.append(s[i - 1]) // Add the character
out.append(count) // Add how many times it repeated
count = 1 // Reset counter
}
}
return out.toString()
}
/* ---------------------------------------------------------
Decompress: turn "a3b2c4" into "aaabbcccc"
Reads a letter, then reads digits, expands them.
--------------------------------------------------------- */
fun decompress(s: String): String {
val out = StringBuilder() // Result string
var currentChar: Char? = null // The character being processed
val number = StringBuilder() // Digits representing the count
for (c in s) {
if (c.isLetter()) { // Found a letter
// If we already have a previous letter + number, expand it
if (currentChar != null && number.isNotEmpty()) {
val count = number.toString().toInt()
out.append(currentChar.toString().repeat(count))
}
currentChar = c // Start new character
number.clear() // Reset number buffer
} else if (c.isDigit()) { // Found a digit
number.append(c) // Build multi-digit number
}
}
// Handle the last character + number pair
if (currentChar != null && number.isNotEmpty()) {
val count = number.toString().toInt()
out.append(currentChar.toString().repeat(count))
}
return out.toString()
}
fun main() {
val s = "wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww"
val c = compress(s)
val d = decompress(c)
println("Original: $s")
println("Compressed: $c")
println("Decompressed: $d")
}
/*
run:
Original: wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww
Compressed: w12b1w10b3w6c4w12
Decompressed: wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww
*/