URL: https://leetcode.com/problems/construct-smallest-number-from-di-string/ Signed-off-by: Matej Focko <me@mfocko.xyz>
28 lines
757 B
Kotlin
28 lines
757 B
Kotlin
class Solution {
|
|
private fun buildSequence(
|
|
pattern: CharArray,
|
|
result: StringBuilder,
|
|
index: Int,
|
|
count: Int,
|
|
): Int {
|
|
var nextCount = count
|
|
when {
|
|
index >= pattern.size -> {}
|
|
pattern[index] == 'I' -> buildSequence(pattern, result, index + 1, index + 1)
|
|
else -> {
|
|
nextCount = buildSequence(pattern, result, index + 1, count)
|
|
}
|
|
}
|
|
|
|
result.append(nextCount + 1)
|
|
return nextCount + 1
|
|
}
|
|
|
|
fun smallestNumber(pattern: String): String =
|
|
StringBuilder().let { result ->
|
|
buildSequence(pattern.toCharArray(), result, 0, 0)
|
|
|
|
result.reverse()
|
|
result.toString()
|
|
}
|
|
}
|