The solution to this easy LC problem is quite simple and I think the code is also self-explanatory so I won’t say that much about this solution.
class Solution {
fun numberOfLines(widths: IntArray, S: String): IntArray {
var currentWidth = 0
var lines = 0
S.forEachIndexed { index, i ->
val width = widths[i.toInt() - 97]
val newWidth = currentWidth + width
when {
newWidth >= 100 -> {
lines++
if(newWidth == 100) currentWidth = 0 else currentWidth = width
}
else -> currentWidth = newWidth
}
}
if(currentWidth > 0) lines++
return intArrayOf(lines, currentWidth)
}
}
Runtime: 140 ms, faster than 100.00% of Kotlin online submissions for Number of Lines To Write String.
Memory Usage: 32 MB, less than 100.00% of Kotlin online submissions for Number of Lines To Write String.
The main idea for this solution is just to iterate through each character while summing up their widths. Then we maintain a counter of lines and increment based on the value of the total computed width.