-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP11.py
More file actions
64 lines (59 loc) · 1.83 KB
/
Copy pathP11.py
File metadata and controls
64 lines (59 loc) · 1.83 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution:
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
lengths = [len(words[i]) for i in range(len(words))]
currLength = 0
start = stop = 0
i = 0
lines = []
while i < len(lengths):
currLength = 0
while i < len(lengths) and currLength + lengths[i] <= maxWidth:
currLength += 1 + lengths[i]
i = i + 1
stop = i - 1
s = ""
line = []
for j in range(start, stop + 1):
line.append(words[j])
start = i
lines.append(line)
results = []
for line in lines[:-1]:
s = ""
lineLength = 0
for w in line:
lineLength += len(w)
spaces = len(line) - 1
lineLength += spaces
toPad = maxWidth - lineLength
if len(line) == 1:
s += line[0] + (" " * toPad)
else:
eachSpace, remSpace = divmod(toPad, spaces)
for w in line[:-1]:
s += w + " " + (" " * eachSpace)
if remSpace:
s += " "
remSpace = remSpace - 1
s += line[-1]
results.append(s)
ll = ""
lastLineLength = 0
for w in lines[-1]:
lastLineLength += len(w)
ll += w + " "
lastLineLength += len(lines[-1]) - 1
lpd = maxWidth - lastLineLength
ll = ll.strip()
ll += " " * lpd
results.append(ll)
return results
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
sol = Solution()
print(sol.fullJustify(words,maxWidth))