URL: https://leetcode.com/problems/partition-labels/ Signed-off-by: Matej Focko <me@mfocko.xyz>
32 lines
786 B
Kotlin
32 lines
786 B
Kotlin
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
|
|
}
|
|
}
|