1. 程式人生 > >python leetcode 68. Text Justification

python leetcode 68. Text Justification

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