kt: add «763. Partition Labels»

URL:	https://leetcode.com/problems/partition-labels/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-03-30 13:36:09 +02:00
parent bb1a26c96f
commit 76d3e0eab1
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

32
kt/partition-labels.kt Normal file
View file

@ -0,0 +1,32 @@
class Solution {
fun partitionLabels(s: String): List<Int> {
val (firstIndex, lastIndex) = IntArray(26) to IntArray(26)
s.withIndex().forEach { (index, c) ->
lastIndex[c - 'a'] = index
}
val sizes = mutableListOf<Int>()
var (start, end) = 0 to 0
s.withIndex().forEach { (i, c) ->
val idx = c - 'a'
if (firstIndex[idx] == 0) {
firstIndex[idx] = i
}
if (end < firstIndex[idx]) {
sizes.add(end - start + 1)
start = i
end = i
}
end = maxOf(end, lastIndex[idx])
}
if (end - start + 1 > 0) {
sizes.add(end - start + 1)
}
return sizes
}
}