leetcode 68:Text Justification(Round Robin算法应用 )

本文详细解析了文本对齐算法的实现,特别是针对LeetCode上的一道经典题目——文本合理化排版。文章介绍了如何使用轮询算法来均匀分布空格,确保每行文字达到指定宽度,同时提供了清晰的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.

题目理解

  1. 给定一些单词串,用数组表示;
  2. 给定一个宽度,一行一个宽度,必须左对齐和右对齐;
  3. 一行之中尽可能多的单词
  4. 如果还有空余的空间,插入空格;
  5. 平均分配空格,无法平均,则左边多,这里就是轮询算法。
  6. 最后一行单词之间不需要多空格。左对齐。也就是后面补空格。

地址

https://leetcode.com/problems/text-justification/description/

例子

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                  "
]

分析与算法

格式化字符; 凑单词数,如果单词+空格的模式累计长度满足maxWidth,那么就需要格式化一下,格式化的方法其实是轮询的插入空格;插入空格的个数则是(width-单词累计长度);
做完一行之后,继续处理下面的单词,如此继续直到处理完所有单词。

伪代码

 while(nums!=null)
 {
    words =  find_max_words_one_line(nums) //为一行找到最多的单词
    format(words,space) //格式化,用轮询插入空格
    nums = nums.subarray(-words)//继续下面的单词
 }

代码

提交通过的代码,换一下方法名。

    def fullJustifyBase(self, words, maxWidth):
        """

        :param words: 单词数组
        :param maxWidth: 一行的最大字符数
        :return:
        """
        res, cur, num_of_letters = [], [], 0
        """
                   num_of_letters:已经保存的字符的个数
                   len(w):当前单词的长度
                   len(cur):多少个单词;也就是多少空格!
        """
        for w in words:
            if num_of_letters + len(w) + len(cur) > maxWidth:
                round_robin(cur,maxWidth - num_of_letters)
                one_line = ''.join(cur)
                res.append(one_line)
                #new one_line
                cur, num_of_letters = [], 0
            cur += [w]
            num_of_letters += len(w)
        return res + [' '.join(cur).ljust(maxWidth)]

   def round_robin(line,space):
    for i in range(space):#round-robin
        line[i %((len(line)-1) or 1)] += ' '#对前n-1进行轮询
    #return line

总结

  1. 轮询算法不断的轮回,如果走到底了,回到起点;简单的mod的应用。当然很多复杂的变形也源于此思路。
  2. 轮询思想的实现利用python非常简洁: cur[i%len] +=’x’ (为数组的每个元素增加一个x,然后不断的从头开始;一遍一遍)
  3. 数组中的字符连接起来; ‘x’.join(array) 转换成string。
  4. 数组添加元素list.append(item)
  5. python实现的字符串的操作简洁性、易读性很高,比java有一定的优势。
  6. 题目理解占比40%, 选择合适的数据结构和算法设计占比40;实现和技巧、调参占比20%。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值