题目链接
https://leetcode.com/problems/text-justification/
题目原文
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.
For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16
.
Return the formatted lines as:
[
"This is an",
"example of text",
"justification. "
]
题目大意
输入一个字符串数组和一个规定长度maxWidth。将这个字符串数组的元素尽可能放到长度的L的字符串中,数组中的字符串不能拆开,一个长度L的字符串包括的若干个字符串之间用相等的空格间隔开;如果空格数不能平均分配,则规定左边的空格数可以大于右边的空格数
解题思路
直接模拟解决即可,但需要注意细节的处理,例如从开始加入元素,长度增加,然后空格+1后继续加入新元素,直到长度大于maxWidth
代码
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
ans = []
i = 0
while i < len(words):
size = 0
begin = i
while i < len(words):
if size == 0:
newsize = len(words[i])
else:
newsize = size + len(words[i]) + 1
if newsize <= maxWidth:
size = newsize
else:
break
i += 1
spaceCnt = maxWidth - size
if i - begin - 1 > 0 and i < len(words):
everyCount = spaceCnt // (i - begin - 1)
spaceCnt %= i - begin - 1
else:
everyCount = 0
j = begin;s=""
while j < i:
if j == begin:
s = words[j]
else:
s += ' ' * (everyCount + 1)
if spaceCnt > 0 and i < len(words):
s += ' '
spaceCnt -= 1
s += words[j]
j += 1
s += ' ' * spaceCnt
ans.append(s)
return ans