Skip to content

Latest commit

 

History

History
166 lines (102 loc) · 4.09 KB

0068._Text_Justification.md

File metadata and controls

166 lines (102 loc) · 4.09 KB

68. Text Justification

难度: Hard

刷题内容

原题连接

内容描述

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.
Example 1:

Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]
Example 2:

Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
Explanation: Note that the last line is "shall be    " instead of "shall     be",
             because the last line must be left-justified instead of fully-justified.
             Note that the second line is also left-justified becase it contains only one word.
Example 3:

Input:
words = ["Science","is","what","we","understand","well","enough","to","explain",
         "to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
Output:
[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "

解题方案

思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******

其实就这个while idx < len(words) and length + idx - 1 <= maxWidth: 循环比较麻烦,只要知道退出循环的原因是什么就好处理了,分两种情况

  1. 一是由于我们的idx out of bound 了,那么说明words[:idx]完全可以组成当前一行
  2. 二是由于当前words[:idx-1]可以组成当前一行,再多加一个word都不行了

这里要注意我们的idx永远会加1,稍微自己搞个例子脑子里跑跑就明白了,beats 100%

class Solution:
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        lines = []
        while words:
            length, idx = 0, 0
            while idx < len(words) and length + idx - 1 <= maxWidth:
                length += len(words[idx])
                idx += 1

            if length + idx - 1 > maxWidth:
                lines.append(words[:idx-1])
                words = words[idx-1:]
            elif idx == len(words):
                lines.append(words[:idx])
                words = words[idx:]tu
        
        res = []
        for s in lines[:-1]:
            res.append(self.fullyHandle(s, maxWidth)) # 前面的行都是 fully-justified
        res.append(self.leftHandle(lines[-1], maxWidth)) # 最后一行是 left-justified 
        return res
    
    def fullyHandle(self, words, maxWidth):
        if len(words) == 1:
            return words[0] + ' ' * (maxWidth - len(words[0]))
        sum_len = sum(len(i) for i in words)
        d, m = divmod(maxWidth - sum_len, len(words) - 1)
        res = ''
        for i, word in enumerate(words):
            if i < m:
                res += word + ' ' * (d + 1)
            else:
                res += word + ' ' * d
        res = res[:maxWidth] + ' ' * (maxWidth - len(res))
        return res

    def leftHandle(self, words, maxWidth):
        res = ' '.join(words)
        res = res + ' ' * (maxWidth - len(res))
        return res