Justified Text
in Programming on String, Interview, Python
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line.
Pad extra spaces ‘ ‘ when necessary so that each line has exactly L characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left justified and no extra space is inserted between words.
Your program should return a list of strings, where each string represents a single line.
Example:
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.
Return the formatted lines as:
[
"This is an",
"example of text",
"justification. "
]
Note: Each word is guaranteed not to exceed L in length.
See Expected Output
S
class Solution:
def justify(self, line, lineWidth, maxWidth, left=False):
if left or len(line)==1:
return ' '.join(line) + ' '*(maxWidth - lineWidth - len(line) + 1)
space_size = (maxWidth - lineWidth) // (len(line)-1)
space_r = (maxWidth - lineWidth) % (len(line)-1)
r = []
for w in line[:-1]:
r.append(w)
r.append(' ' * space_size)
if space_r > 0:
r.append(' ')
space_r -= 1
return ''.join(r+line[-1])
# @param A : list of strings
# @param B : integer
# @return a list of strings
def fullJustify(self, A, B):
r, line, lineWidth = [], [], 0
for w in A:
if lineWidth + len(w) + len(line) <= B:
line.append(w)
lineWidth += len(w)
else:
r.append(self.justify(line, lineWidth, B))
line, lineWidth = [w], len(w)
r.append(self.justify(line, lineWidth, B, left=True))
return r