-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0068-text-justification.py
33 lines (28 loc) · 1.12 KB
/
0068-text-justification.py
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
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
res = []
line = [] # Words in current line
length = 0 # Current line length
i = 0
while i < len(words):
if length + len(line) + len(words[i]) > maxWidth:
# Line complete
extra_space = maxWidth - length
word_cnt = len(line) - 1
spaces = extra_space // max(1, word_cnt)
remainder = extra_space % max(1, word_cnt)
for j in range(max(1, len(line) - 1)):
line[j] += " " * spaces
if remainder:
line[j] += " "
remainder -= 1
res.append("".join(line))
line, length = [], 0 # Reset line and length
line.append(words[i])
length += len(words[i])
i += 1
# Handling the last line
last_line = " ".join(line)
trail_spaces = maxWidth - len(last_line)
res.append(last_line + (trail_spaces * " "))
return res