20ms 100% 虽然是hard题,但就是考察编写代码的能力。有失于hard题的水准
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
res=[]
count=0
tmp=[]
for w in words:
if count+len(w)>maxWidth:
if len(tmp)==1:
res.append(tmp[0]+' '*(maxWidth-len(tmp[0])))
else:
Snum=maxWidth-count+len(tmp)
Enum=Snum//(len(tmp)-1)
index=Snum%(len(tmp)-1)
s=''
for i in range(len(tmp)-1):
if i<index:
s=s+tmp[i]+' '*(Enum+1)
else:
s=s+tmp[i]+' '*Enum
s+=tmp[-1]
res.append(s)
tmp=[w]
count=len(w)+1
else:
count+=len(w)+1
tmp.append(w)
if len(tmp)==1:
res.append(tmp[0]+' '*(maxWidth-len(tmp[0])))
else:
s=''
for i in range(len(tmp)-1):
s=s+tmp[i]+' '
s+=tmp[-1]
s=s+' '*(maxWidth-len(s))
res.append(s)
return res