Skip to content

Commit bfc3639

Browse files
authored
Create 0068-text-justification.kt
1 parent b6b711a commit bfc3639

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

kotlin/0068-text-justification.kt

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

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy