068. Text Justification
Question 68
https://leetcode.com/problems/text-justification/
Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidthcharacters 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 maxWidth 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.
Note:
A word is defined as a character sequence consisting of non-space characters only.
Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
The input array
words
contains at least one word.
Example 1:
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
"This is an",
"example of text",
"justification. "
]
Answer
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
current_string = ""
Ans_list, current_list = [], []
for word in words:
if len(current_string) + len(word) + len(current_list) > maxWidth:
if len(current_list) == 1:
Ans_list.append( current_list[0] + " "*(maxWidth - len(current_list[0])) )
else:
rest_space = maxWidth - len(current_string)
split_space, begin_space = divmod( rest_space, len(current_list) - 1 )
current_string = (" "*(split_space+1)).join(current_list[:begin_space+1])
current_string += " "*(split_space)
current_string += (" "*(split_space)).join(current_list[begin_space+1:])
Ans_list.append(current_string)
# clear all
current_string = ""
del current_list[:]
# add new word
current_list.append(word)
current_string += word
Ans_list.append( ' '.join(current_list) + ' '*(maxWidth - len(current_string) - len(current_list) + 1) )
return Ans_list
Last updated