Skip to content

Commit 98a3a80

Browse files
committed
no message
1 parent fd5bc7c commit 98a3a80

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

problems/text-justification.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""
2+
The description of this problem is unclear.
3+
"Extra spaces between words should be distributed as evenly as possible." Should be "Extra spaces between words IN EACH LINE should be distributed as evenly as possible."
4+
So the problem in short is:
5+
1. Every line should have as many as word as possible. But they should be separate by space or spaces.
6+
2. Mid align all the line. Except the last line and the lines with one word.
7+
3. For mid align, distribute space evenly, if there are extra spaces, it should be located left. For example 5 spaces distribute to 2 places, it should be 3 2, not 2 3. 7 spaces distribute to 3 places, it should be 3 2 2, not 2 3 2, not 2 2 3.
8+
9+
Time: O(N), N is the number of words.
10+
Space: O(W), W is maxWidth for keeping strings in currLine. Can further reduce to O(1) using only index.
11+
"""
12+
class Solution(object):
13+
def fullJustify(self, words, maxWidth):
14+
def canAddToCurrLine(word, currLineStringLength):
15+
currWidth = len(currLine)-1 + currLineStringLength # space+currLineStringLength
16+
return currWidth+len(word)+1<=maxWidth
17+
18+
def leftAlign(currLine):
19+
line = ''
20+
21+
for word in currLine:
22+
line += word + ' '
23+
line = line[:-1] #remove last space
24+
25+
line += ' '*(maxWidth-len(line))
26+
return line
27+
28+
def midAlign(currLine, currLineStringLength):
29+
line = ''
30+
31+
totalSpaceCount = maxWidth-currLineStringLength
32+
extraSpaceCount = totalSpaceCount%(len(currLine)-1)
33+
spaceCount = totalSpaceCount-extraSpaceCount
34+
spaces = ' '*(totalSpaceCount/(len(currLine)-1))
35+
36+
for word in currLine:
37+
line += word
38+
if spaceCount>0:
39+
line += spaces
40+
spaceCount -= len(spaces)
41+
42+
if extraSpaceCount>0:
43+
line += ' '
44+
extraSpaceCount -= 1
45+
46+
return line
47+
48+
currLineStringLength = 0
49+
currLine = []
50+
ans = []
51+
52+
i = 0
53+
while i<len(words):
54+
if canAddToCurrLine(words[i], currLineStringLength):
55+
currLine.append(words[i])
56+
currLineStringLength += len(words[i])
57+
i += 1
58+
else:
59+
if len(currLine)==1:
60+
ans.append(leftAlign(currLine)) #line with one word align left
61+
else:
62+
ans.append(midAlign(currLine, currLineStringLength))
63+
64+
currLine = []
65+
currLineStringLength = 0
66+
67+
ans.append(leftAlign(currLine)) #last line should always align left
68+
return ans

0 commit comments

Comments
 (0)