class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
out = []
line = [words[0]]
lineWidth = len(words[0])
for i in range(1, len(words)):
if lineWidth + len(words[i]) + 1 <= maxWidth:
lineWidth += len(words[i]) + 1
line.append(words[i])
else:
out.append(self.helper(line, lineWidth, maxWidth))
line = [words[i]]
lineWidth = len(words[i])
out.append(self.helper(line, lineWidth, maxWidth, True))
return out
def helper(self, line, lineWidth, maxWidth, flag=False):
strLine = line[0]
num = len(line)
if flag:
for i in range(1, num):
strLine += ' ' + line[i]
strLine += ' ' * (maxWidth-lineWidth)
return strLine
if num>1:
totalSpaces = maxWidth - lineWidth + num - 1
avgSpaces = totalSpaces/(num-1)
moreSpaces = totalSpaces%(num-1)
for i in range(1, num):
strLine += ' ' * (avgSpaces + (1 if i<moreSpaces+1 else 0)) + line[i]
else:
strLine = line[0] + ' '*(maxWidth-lineWidth)
return strLine
0068
最新推荐文章于 2024-06-06 16:07:02 发布