https://leetcode.com/problems/text-justification/
思路是这样的:
1.先分行
2.将这一行输出
分行的方法是 前i个字符串和i-1个空格的长度小于Max i自加
如果除了这i个字符串没有别的了 就用last()方法输出(输出最后一行的方法)
如果还有后续字符 就用 output()方法输出
判断是否为最后一行用了needle变量
每次分完一行 就将分完的删掉 所以 只要words[]还有内容 就要一直重复分行
class Solution:
# @param {string[]} words
# @param {integer} maxWidth
# @return {string[]}
def output(self,words,temp,maxWidth):
alllength=0
newstring=''
n=0
average=0
extra=0
for i in words[0:temp+1]:
alllength=alllength+len(i)
if temp!=0:
average=(maxWidth-alllength)/temp
extra=(maxWidth-alllength)%temp
if temp==0:
newstring=words[0]+' '*(maxWidth-len(words[0]))
else:
for i in words[0:temp]:
newstring=newstring+i+' '*average
if n<extra:
newstring=newstring+' '
n=n+1
newstring=newstring+words[temp]
return newstring
def last(self,words,maxWidth):
lastline=''
if maxWidth==len(words[0]):
return words[0]
for i in words:
lastline=lastline+i+' '
n=len(lastline)
lastline=lastline+(maxWidth-n)*' '
return lastline
def fullJustify(self, words, maxWidth):
sol=[]
temp=0
lastline=''
if len(words)==1:
lastline=Solution().last(words,maxWidth)
sol.append(lastline)
return sol
else:
while len(words)>0:
temp=0
length=len(words[0])
all=0
needle=0
while length+temp<=maxWidth:
if temp!=len(words)-1:
temp=temp+1
length=length+len(words[temp])
else:#temp为最后一个的index
needle=1
break
if needle==0:
temp=temp-1
sol.append(Solution().output(words,temp,maxWidth))
words=words[temp+1:]
else:
lastline1=''
lastline1=Solution().last(words,maxWidth)
sol.append(lastline1)
break
return sol