题目
给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。
你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ’ ’ 填充,使得每行恰好有 maxWidth 个字符。
要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。
文本的最后一行应为左对齐,且单词之间不插入额外的空格。
说明:
单词是指由非空格字符组成的字符序列。
每个单词的长度大于 0,小于等于 maxWidth。
输入单词数组 words 至少包含一个单词。
示例
输入:
words = [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”]
maxWidth = 16
输出:
[
“This is an”,
“example of text”,
"justification. "
]
输入:
words = [“What”,“must”,“be”,“acknowledgment”,“shall”,“be”]
maxWidth = 16
输出:
[
“What must be”,
"acknowledgment ",
"shall be "
]
解释: 注意最后一行的格式应为 "shall be " 而不是 “shall be”,
因为最后一行应为左对齐,而不是左右两端对齐。
第二行同样为左对齐,这是因为这行只包含一个单词。
输入:
words = [“Science”,“is”,“what”,“we”,“understand”,“well”,“enough”,“to”,“explain”,
“to”,“a”,“computer.”,“Art”,“is”,“everything”,“else”,“we”,“do”]
maxWidth = 20
输出:
[
“Science is what we”,
“understand well”,
“enough to explain to”,
“a computer. Art is”,
“everything else we”,
"do "
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/text-justification
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
想法
分为2个大方向:
1、提取出每行的单词。
控制每行的判断条件: while(varsum<=maxWidth+1 and i<len(words)):
varsum<=maxWidth+1:因为每次判断长度时,添加一个单词时同时添加了一个空格。
例如极端情况:【“enough”,“to”,“explain”,“to”】,一行不能超过20个。总的单词长度为17,添加了3个空格,为20;但是总判断长度为21。
2、按行导出且安置空格。
额外添加的空格可以看作在均分空格基础上添加。
均分空格为:总的空格数 / (个数-1)
额外空格为:总的空格数 % (个数-1),且规律:额外添加的空格肯定小于(个数-1)
因此空格数:
先把必须的均分空格添上去。额外的从头开始添加,每次添加1个就行了,添加完了额外空格数-1
一行只有1个单词 和 最后一行特殊情况要分别讨论。
实现
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
i,varsum,long,var=0,0,0,0
varl,res,longl,out,rowout=list(),list(),list(),list(),str()
#提取每行的单词
while(i<len(words)):
varsum=len(words[i])+1
while(varsum<=maxWidth+1 and i<len(words)):
varl.append(words[i])
long+=len(words[i])
if i+1<len(words):
i+=1
varsum+=len(words[i])+1
else:
i+=1
res.append(varl)
longl.append(long)
long=0
varl=[]
#安置空格
for i in range(len(res)):
sc=maxWidth-longl[i]
if len(res[i])==1: #1个单词情况
rowout+=str(res[i][0])
for k in range(sc):
rowout+=" "
elif i==len(res)-1: #最后一行情况
for q in range(len(res[i])):
if q != len(res[i]) - 1:
rowout+=str(res[i][q])
rowout+=" "
sc-=1
else:
rowout+=str(res[i][q])
for p in range(sc):
rowout+=" "
else:
ix = sc/(len(res[i])-1)
iy=sc%(len(res[i])-1)
for j in range(len(res[i])):
if j != len(res[i]) - 1:
rowout += str(res[i][j])
for m in range(int(ix)):#均分的空格数先添加
rowout+=" "
if iy != 0:
rowout+=" "
iy-=1
else:
rowout+=str(res[i][j])
out.append(rowout)
rowout=""
return(out)