Friday, September 19, 2014

Leetcode: Text Justification @Python

class Solution:
    # @param words, a list of strings
    # @param L, an integer
    # @return a list of strings
    def fullJustify(self, words, L):
        def gen(queue,num,blanks):
            line=[]
            if num==1:
                item=queue.pop()
                line=item+''.join([' ']*(L-len(item)))
                rst.append(line)
                return
            spare=blanks%(num-1)
            while queue:
                word=queue.popleft()
                space=blanks//(num-1)+1 if spare>0 else blanks//(num-1)
                spare-=1
                if queue:
                    line.append(word+''.join([' ']*space))
                else:
                    line.append(word)
            rst.append(''.join(line))
            
        queue=collections.deque([])
        rst=[]
        n=0
        num=0
        while words:
            if n+len(words[0])<=L:
                queue.append(words[0])
                n+=len(words[0])+1
                num+=1
                words.pop(0)
            else:
                blanks=L-n+num if n<=L else num-1 
                gen(queue,num,blanks)
                num=0
                n=0
        line=' '.join(list(queue))
        rst.append(line+''.join([' ']*(L-len(line))))
        return rst

No comments :

Post a Comment