-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0068-text-justification.kt
42 lines (36 loc) · 1.31 KB
/
0068-text-justification.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//opted out of using StringBuilder, instead used Kotlins plus operator to create new Strings
class Solution {
fun fullJustify(words: Array<String>, maxWidth: Int): List<String> {
val res = mutableListOf<String>()
var line = mutableListOf<String>()
var length = 0
var i = 0
while (i < words.size) {
if (length + line.size + words[i].length > maxWidth) {
val extraSpace = maxWidth - length
val spaces = extraSpace / maxOf(1, line.size - 1)
var remainder = extraSpace % maxOf(1, line.size - 1)
for (j in 0 until maxOf(1, line.lastIndex)) {
line[j] += " ".repeat(spaces)
if (remainder > 0) {
line[j] += " "
remainder--
}
}
var whole = ""
for (l in line) whole += l
res.add(whole)
line.clear()
length = 0
}
line.add(words[i])
length += words[i].length
i++
}
var lastLine = "" + line.joinToString(" ")
val trailSpace = maxWidth - lastLine.length
lastLine += " ".repeat(trailSpace)
res.add(lastLine)
return res
}
}