Skip to content

Commit

Permalink
add Kotlin solution for 763. Partition Labels
Browse files Browse the repository at this point in the history
  • Loading branch information
technophilist committed May 3, 2023
1 parent 8bc0529 commit 2c9ac35
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions kotlin/0763-partition-labels.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Solution {
fun partitionLabels(s: String): List<Int> {
if (s.length == 1) return listOf(1)
val lastIndexOfChar = mutableMapOf<Char, Int>().apply {
s.forEachIndexed { index, char -> this[char] = index }
}
val partitions = mutableListOf<Int>()
var l = 0
while (l in s.indices) {
// keep moving l to find the first char that has a last occurrence greater than l
while (l == lastIndexOfChar[s[l]]) {
// if l is at the one-and-only occurrence of the char s[l], make a partition and move l
partitions.add(1)
l++
if (l > s.lastIndex) return partitions
}

var r = lastIndexOfChar.getValue(s[l])
var j = l + 1
while (j <= r) {
if (lastIndexOfChar.getValue(s[j]) <= r){
j++
continue
}
r = lastIndexOfChar.getValue(s[j])
j++
}
partitions.add((r - l) + 1)
l = r + 1
}
return partitions
}
}

0 comments on commit 2c9ac35

Please sign in to comment.