kt: add «3163. String Compression III»
URL: https://leetcode.com/problems/string-compression-iii/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
340d234a4f
commit
383579f508
1 changed files with 32 additions and 0 deletions
32
kt/string-compression-iii.kt
Normal file
32
kt/string-compression-iii.kt
Normal file
|
@ -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}"
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue