From 383579f508f9e24912eea87314b13d6982fc978d Mon Sep 17 00:00:00 2001
From: Matej Focko <me@mfocko.xyz>
Date: Mon, 4 Nov 2024 22:21:14 +0100
Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB3163.=20String=20Compression?=
 =?UTF-8?q?=20III=C2=BB?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

URL:	https://leetcode.com/problems/string-compression-iii/
Signed-off-by: Matej Focko <me@mfocko.xyz>
---
 kt/string-compression-iii.kt | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
 create mode 100644 kt/string-compression-iii.kt

diff --git a/kt/string-compression-iii.kt b/kt/string-compression-iii.kt
new file mode 100644
index 0000000..7cdab22
--- /dev/null
+++ b/kt/string-compression-iii.kt
@@ -0,0 +1,32 @@
+class Solution {
+    private data class State(val compressed: MutableList<Pair<Int, Char>>, val count: Int, val character: Char) {
+        private fun add() {
+            if (count <= 0) {
+                return
+            }
+
+            compressed.add(count to character)
+        }
+
+        fun update(c: Char): State {
+            if (c != character || count >= 9) {
+                add()
+                return State(compressed, 1, c)
+            }
+
+            return State(compressed, 1 + count, c)
+        }
+
+        fun finalize(): State {
+            add()
+            return State(compressed, 0, '_')
+        }
+    }
+
+    fun compressedString(word: String): String =
+        word.fold(State(mutableListOf(), 0, word[0])) { acc, it ->
+            acc.update(it)
+        }.finalize().compressed.joinToString(separator = "") {
+            "${it.first}${it.second}"
+        }
+}