068. Text Justification
Question 68
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
"This is an",
"example of text",
"justification. "
]Answer
Last updated
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
"This is an",
"example of text",
"justification. "
]Last updated
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_listclass Solution(object):
def fullJustify(self, words, maxWidth):
words_len = len(words)
current_string = ""
Ans_list = []
current_words = 0
current_list = []
i = 0
while i < words_len:
if len(current_string) + len(words[i]) + 1 > maxWidth:
if current_words == 1:
current_string += " "*(maxWidth - len(current_string))
elif current_string == "":
current_string = words[i]
current_string += " "*(maxWidth - len(current_string))
i += 1
else :
rest_space = maxWidth - len(current_string)
if not rest_space % (current_words - 1):
split_space = int(rest_space / (current_words - 1)) + 1
current_string = (" "*split_space).join(current_list)
else:
split_space = int( rest_space // (current_words - 1) ) + 1
begin_space = rest_space % (current_words - 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)
current_string = ""
current_words = 0
del current_list[:]
elif i == words_len -1 :
current_list.append(words[i])
current_string = " ".join(current_list)
current_string += " "*(maxWidth - len(current_string))
Ans_list.append(current_string)
break
else:
current_list.append(words[i])
current_string = " ".join(current_list)
current_words += 1
i += 1
return Ans_list