Leetcode 68. Text Justification

Problem

Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ’ ’ when necessary so that each line has exactly maxWidth characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

Note:

  • A word is defined as a character sequence consisting of non-space characters only.
  • Each word’s length is guaranteed to be greater than 0 and not exceed maxWidth.
  • The input array words contains at least one word.

Algorithm

Imitate with greedy.

Code

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        dLen = len(words)
        wLen = [0] * dLen
        for i in range(dLen):
            wLen[i] = len(words[i])
        
        ouput = []
        index = 0
        while index < dLen:
            start = index
            sumLen = 0
            while index < dLen and sumLen + wLen[index] <= maxWidth:
                if sumLen > 0:
                    sumLen += 1
                sumLen += wLen[index]
                index += 1
            if sumLen > maxWidth:
                sumLen -= wLen[index-1] + 1
                index -= 1
            
            line = ""
            if index < dLen and index - start > 1:
                blank = (maxWidth - sumLen) // (index - start - 1) + 1
                left = maxWidth - sumLen - (blank - 1) * (index - start - 1)
                while start < index-1:
                    line += words[start]
                    line += " " * blank
                    if left:
                        left -= 1
                        line += " "
                    start += 1
                line += words[index-1]
            else:
                sumLen = 0
                while start < index:
                    line += words[start]
                    sumLen += wLen[start]
                    if sumLen < maxWidth:
                        line += " " 
                        sumLen += 1
                    start += 1
                while sumLen < maxWidth:
                    sumLen += 1
                    line += " " 
            
            ouput.append(line)
            
        return ouput
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值